C# 如何判斷兩個檔案內容是否相同的方法

來源:互聯網
上載者:User

該雜湊演算法為一個檔案產生一個小的二進位“指紋”,從統計學的角度來看,不同的檔案不可能產生相同的雜湊碼

要產生一個雜湊碼,必須首先建立一個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();
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.