C#比较两个文件内容是否相同

今天看到项目的比较文件是先将所有字节读出来,然后逐一进行比较,想找找有没有可以优化的地方。在网上看了一下,有比较哈希码的,验证了一下,发现不管是文件开始就不相同,还是文件末尾才不相同,都比较耗时。

C#比较两个文本文件的内容是否相等 - 五点 - 博客园 (cnblogs.com)

测试文件大小:10000KB

一、比较哈希码

先将文件内容转成哈希码,然后进行比较。

    public static bool CompareFile(string sourceFilePath, string destFilePath)
    {
        if (string.IsNullOrEmpty(sourceFilePath) || string.IsNullOrEmpty(destFilePath))
        {
            return false;
        }
        if (!File.Exists(sourceFilePath)|| !File.Exists(destFilePath))
        {
            return false;
        }
        using (HashAlgorithm hash = HashAlgorithm.Create())
        {
            using (FileStream file1 = new FileStream(sourceFilePath, FileMode.Open), file2 = new FileStream(destFilePath, FileMode.Open))
            {
                byte[] hashByte1 = hash.ComputeHash(file1);//哈希算法根据文本得到哈希码的字节数组
                byte[] hashByte2 = hash.ComputeHash(file2);
                string str1 = BitConverter.ToString(hashByte1);//将字节数组装换为字符串
                string str2 = BitConverter.ToString(hashByte2);
                return str2 == str1;
            }
        }
        return false;
    }

在两个转哈希码的方法上加上测试代码。发现,比较耗时。

 

 二、逐字符比较

  public static bool CompareFile(string sourceFilePath, string destFilePath)
    {
        if (string.IsNullOrEmpty(sourceFilePath) || string.IsNullOrEmpty(destFilePath))
        {
            return false;
        }
        if (!File.Exists(sourceFilePath) || !File.Exists(destFilePath))
        {
            return false;
        }
        byte[] _source = File.ReadAllBytes(sourceFilePath);
        byte[] _dest = File.ReadAllBytes(destFilePath);
        if (_source.Length != _dest.Length)
        {
            return false;
        }
        for (int i = 0; i < _source.Length; ++i)
        {
            if (_source[i] != _dest[i])
            {
                return false;
            }
        }
        return true;
    }

 在逐字符的比较函数上加上测试代码。

如果文件开始就不相同,比较耗时约等于读取文件的耗时。

如果文件末尾才不相同,比较耗时也比先转哈希码再比较快很多。

总结:

当前测试的文件是10000KB的存数字文本,没有进行其他文件更大的测试。先读取文件二进制数据逐一比较比将文件转成哈希码进行比较效率更优。

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值