• 【转】【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);//比较哈希码 
                   } 
               } 
           } 
  • 相关阅读:
    报数游戏
    Dynamics CRM 2013 初体验(2):UI
    Lucene.net常见功能实现知识汇总
    hdu 1853 最小费用流好题 环的问题
    MessagerService总结
    [置顶] Android EditText/TextView使用SpannableString显示复合文本
    MySQL Dll语句
    JavaScript表单验证
    intellij—idea14 注冊机
    OL记载Arcgis Server切片
  • 原文地址:https://www.cnblogs.com/mqxs/p/5475191.html
Copyright © 2020-2023  润新知