






















Since it is slow and has low performance to compare to files byte by byte, we could use MD5 algorithm to computer the Hash Code of the FileStream for specified files to check whether two files have the same content. .Net has MD5 algorithm inside, you can search MD5 in MSDN for detail. You can download the full sample code and compiled program: https://files.cnblogs.com/davidullua/FileComparer.zip
Here's the sample code to compute hash code of a file:
/// <summary>
/// to computer HashCode of a File, different files will generate different HashCode
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static string ComputeHashCode(string fileName)
{
if(!File.Exists(fileName))
{
throw new FileNotFoundException("File does not exist",fileName);
} 
Stream fileStream = File.OpenRead(fileName);
try
{
MD5CryptoServiceProvider MD5Alg = new MD5CryptoServiceProvider(); 
byte[] hashValue = MD5Alg.ComputeHash(fileStream); 
return BitConverter.ToString(hashValue);
} 
catch
{
throw;
}
finally
{
fileStream.Close();
}
}
Here's the code to compare two files' HashCode:
/// <summary>
/// used to Compare Two files' HashCode, return true or false
/// </summary>
/// <param name="fileOne"></param>
/// <param name="fileTwo"></param>
/// <returns></returns>
public static bool CompareFiles(string fileOne, string fileTwo)
{
if(!File.Exists(fileOne) || !File.Exists(fileTwo))
{
throw new FileNotFoundException("File does not exist");
}
try
{
string stringValue1 = ComputeHashCode(fileOne);
string stringValue2 = ComputeHashCode(fileTwo); 
return (stringValue1.Equals(stringValue2));
} 
catch
{
throw;
} 

}
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。