gpt4 book ai didi

c# - 在 C# 中比较二进制文件

转载 作者:IT王子 更新时间:2023-10-29 04:10:26 25 4
gpt4 key购买 nike

我想比较两个二进制文件。其中一个已经存储在服务器上,并且在我最初存储它时在数据库中有一个预先计算的 CRC32。

我知道如果CRC不一样,那么文件肯定不一样。但是,如果 CRC 相同,我不知道这些文件是相同的。因此,我正在寻找一种非常有效的方法来比较两个流:一个来自发布的文件,一个来自文件系统。

我不是流方面的专家,但我很清楚,就内存使用而言,我很容易搬起石头砸自己的脚。

最佳答案

static bool FileEquals(string fileName1, string fileName2)
{
// Check the file size and CRC equality here.. if they are equal...
using (var file1 = new FileStream(fileName1, FileMode.Open))
using (var file2 = new FileStream(fileName2, FileMode.Open))
return FileStreamEquals(file1, file2);
}

static bool FileStreamEquals(Stream stream1, Stream stream2)
{
const int bufferSize = 2048;
byte[] buffer1 = new byte[bufferSize]; //buffer size
byte[] buffer2 = new byte[bufferSize];
while (true) {
int count1 = stream1.Read(buffer1, 0, bufferSize);
int count2 = stream2.Read(buffer2, 0, bufferSize);

if (count1 != count2)
return false;

if (count1 == 0)
return true;

// You might replace the following with an efficient "memcmp"
if (!buffer1.Take(count1).SequenceEqual(buffer2.Take(count2)))
return false;
}
}

关于c# - 在 C# 中比较二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/968935/

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