gpt4 book ai didi

c# - 如何使用 .NET 快速比较 2 个文件?

转载 作者:IT王子 更新时间:2023-10-29 03:33:18 33 4
gpt4 key购买 nike

Typical approaches建议通过 FileStream 读取二进制文件并逐字节比较。

  • 校验和比较(例如 CRC)会更快吗?
  • 是否有可以为文件生成校验和的 .NET 库?

最佳答案

最慢的方法是逐字节比较两个文件。我能想到的最快速度是类似的比较,但不是一次一个字节,而是使用大小为 Int64 的字节数组,然后比较结果数字。

这是我想出的:

    const int BYTES_TO_READ = sizeof(Int64);

static bool FilesAreEqual(FileInfo first, FileInfo second)
{
if (first.Length != second.Length)
return false;

if (string.Equals(first.FullName, second.FullName, StringComparison.OrdinalIgnoreCase))
return true;

int iterations = (int)Math.Ceiling((double)first.Length / BYTES_TO_READ);

using (FileStream fs1 = first.OpenRead())
using (FileStream fs2 = second.OpenRead())
{
byte[] one = new byte[BYTES_TO_READ];
byte[] two = new byte[BYTES_TO_READ];

for (int i = 0; i < iterations; i++)
{
fs1.Read(one, 0, BYTES_TO_READ);
fs2.Read(two, 0, BYTES_TO_READ);

if (BitConverter.ToInt64(one,0) != BitConverter.ToInt64(two,0))
return false;
}
}

return true;
}

在我的测试中,我能够看到这比简单的 ReadByte() 场景高出近 3:1。平均超过 1000 次运行,我在 1063 毫秒时得到这个方法,在 3031 毫秒时得到下面的方法(直接逐字节比较)。哈希总是以亚秒级的速度返回,平均大约为 865 毫秒。此测试使用的是约 100MB 的视频文件。

这是我使用的 ReadByte 和散列方法,用于比较:

    static bool FilesAreEqual_OneByte(FileInfo first, FileInfo second)
{
if (first.Length != second.Length)
return false;

if (string.Equals(first.FullName, second.FullName, StringComparison.OrdinalIgnoreCase))
return true;

using (FileStream fs1 = first.OpenRead())
using (FileStream fs2 = second.OpenRead())
{
for (int i = 0; i < first.Length; i++)
{
if (fs1.ReadByte() != fs2.ReadByte())
return false;
}
}

return true;
}

static bool FilesAreEqual_Hash(FileInfo first, FileInfo second)
{
byte[] firstHash = MD5.Create().ComputeHash(first.OpenRead());
byte[] secondHash = MD5.Create().ComputeHash(second.OpenRead());

for (int i=0; i<firstHash.Length; i++)
{
if (firstHash[i] != secondHash[i])
return false;
}
return true;
}

关于c# - 如何使用 .NET 快速比较 2 个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1358510/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com