該雜湊演算法為一個檔案產生一個小的二進位“指紋”,從統計學的角度來看,不同的檔案不可能產生相同的雜湊碼
要產生一個雜湊碼,必須首先建立一個HashAlgorithm對象,通過HashAlgorithm.Create方法來完成。然後調用
HashAlgorithm.ComputeHash方法,它會返回一個儲存雜湊碼的位元組數組,再使用BitConverter.Tostring()將其
裝換為字串進行比較。
源碼如下:
複製代碼 代碼如下:public static bool isValidFileContent(string filePath1, string filePath2)
{
//建立一個雜湊演算法對象
using (HashAlgorithm hash = HashAlgorithm.Create())
{
using (FileStream file1 = new FileStream(filePath1, FileMode.Open),file2=new FileStream(filePath2,FileMode.Open))
{
byte[] hashByte1 = hash.ComputeHash(file1);//雜湊演算法根據文本得到雜湊碼的位元組數組
byte[] hashByte2 = hash.ComputeHash(file2);
string str1 = BitConverter.ToString(hashByte1);//將位元組數組裝換為字串
string str2 = BitConverter.ToString(hashByte2);
return (str1==str2);//比較雜湊碼
}
}
}
使用該函數的主函數
複製代碼 代碼如下:static void Main(string[] args)
{
string filePath1 = @"f:/1.txt";
string filePath2 = @"f:/2.txt";
bool valid=isValidFileContent(filePath1, filePath2);
Console.WriteLine(valid.ToString());
Console.ReadKey();
}