【转】【C#】判断两个文件是否相同

使用System.security.Cryptography.HashAlgorithm类为每个文件生成一个哈希码,然后比较两个哈希码是否相同

该哈希算法为一个文件生成一个小的二进制“指纹”,从统计学的角度来看,不同的文件不可能生成相同的哈希码

要生成一个哈希码,必须首先创建一个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);//比较哈希码 
               } 
           } 
       } 
原文地址:https://www.cnblogs.com/mqxs/p/5475191.html