如何使用.NET比较2个文件? [英] How to compare 2 files fast using .NET?

查看:156
本文介绍了如何使用.NET比较2个文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

典型的方法建议通过FileStream读取二进制文件并逐字节比较。 / p>


  • 校验和比较如CRC是否更快?

  • 是否有任何.NET库生成文件的校验和?


解决方案

校验和比较很可能比逐字节比较。



为了生成校验和,您需要加载文件的每个字节,并对其进行处理。然后,您必须在第二个文件上执行此操作。处理将几乎肯定比比较检查慢。



关于生成校验和:您可以轻松地使用加密类。以下是使用C#生成MD5校验和的简短示例。



但是,如果您可以预先计算测试或基准情况的校验和,则校验和可能更快,更有意义。如果您有一个现有文件,并且您正在检查新文件是否与现有文件相同,那么预先计算现有文件的校验和将意味着只需要在DiskIO上执行一次,新文件这可能比逐字节比较更快。


Typical approaches recommend reading the binary via FileStream and comparing it byte-by-byte.

  • Would a checksum comparison such as CRC be faster?
  • Are there any .NET libraries that can generate a checksum for a file?

解决方案

A checksum comparison will most likely be slower than a byte-by-byte comparison.

In order to generate a checksum, you'll need to load each byte of the file, and perform processing on it. You'll then have to do this on the second file. The processing will almost definitely be slower than the comparison check.

As for generating a checksum: You can do this easily with the cryptography classes. Here's a short example of generating an MD5 checksum with C#.

However, a checksum may be faster and make more sense if you can pre-compute the checksum of the "test" or "base" case. If you have an existing file, and you're checking to see if a new file is the same as the existing one, pre-computing the checksum on your "existing" file would mean only needing to do the DiskIO one time, on the new file. This would likely be faster than a byte-by-byte comparison.

这篇关于如何使用.NET比较2个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆