码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2016-05-09 20:26:09      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:

使用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);//比较哈希码 
               } 
           } 
       } 

 

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

标签:

原文地址:http://www.cnblogs.com/mqxs/p/5475191.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!