IEqualityComparer<FileInfo> using MD5 Hash





5.00/5 (3 votes)
The presented code snippet compares two given files using the IEqualityComparer.
Introduction
The presented code snippet compares two given files using the IEqualityComparer
.
The comparison does the following:
- Use the FileInfo's equality operator (==) to try to determine whether these are the same instances of the FileInfo class
- If one of the objects is null
, they can't represent the same files, thus false is returned
- If the file path is for both objects the same, true is returned since the file must be the same
- If the file sizes differ, the files can't be the same either thus false is returned
- And at the end we resort to comparing the MD5 hash of both files.
Background
Please keep in mind that this implementation reads the file contents into the memory to create the MD5 for each file. If you're trying to compare very large files, this may slow down your application considerably.
The code
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> for files using <see cref="FileInfo"/>
/// </summary>
public class FileMd5EqualityComparer : IEqualityComparer<FileInfo>
{
/// <summary>
/// See <see cref="IEqualityComparer{T}.Equals(T, T)"/>
/// </summary>
public bool Equals(FileInfo x, FileInfo y)
{
// Use basic comparison
if(x == y)
{
return true;
}
// if one of both parameters is null, they can't be
// the same - Except both are null, but this case is
// handled above.
if(x == null || y == null)
{
return false;
}
// If both file paths are the same, the
// files must be the same.
if(x.FullName == y.FullName)
{
return true;
}
// The files can't be equal if they don't
// have the same size
if(x.Length != y.Length)
{
return false;
}
// At last, compare the MD5 of the files.
var md5X = GetMd5(x.FullName);
var md5Y = GetMd5(y.FullName);
return md5X == md5Y;
}
/// <summary>
/// See <see cref="IEqualityComparer{T}.Equals(T, T)"/>
/// </summary>
public int GetHashCode(FileInfo obj)
{
return obj.GetHashCode();
}
/// <summary>
/// Returns the MD5 of the file at <paramref name="filePath"/>
/// as string
/// </summary>
private string GetMd5(string filePath)
{
using (var md5 = MD5.Create())
{
using (var stream = File.OpenRead(filePath))
{
return Encoding.Default.GetString(md5.ComputeHash(stream));
}
}
}
}
History
2018-05-25 Initial version