对比二进制文件在C# [英] Compare binary files in C#
问题描述
我要比较两个二进制文件。其中一个已经存储在数据库中的,当我保存它原本是pre-CRC32计算服务器上。
我知道,如果CRC不同,则这些文件肯定是不同的。然而,如果CRC是一样的,不知道该文件是。所以,我在找比较这两个流的一个很好的有效的方式:从文件系统中的一个从发布的文件和一个
我不是流的专家,但我很清楚,我可以轻松拍摄自己的脚在这里尽可能的内存使用情况而言。
静态布尔FileEquals(字符串文件名1,串文件名2)
{
//检查文件大小和CRC平等这里..如果他们是平等的......
使用(VAR文件1 =新的FileStream(文件名,FileMode.Open))
使用(VAR文件2 =新的FileStream(文件名,FileMode.Open))
返回FileStreamEquals(文件1,文件2);
}静态布尔FileStreamEquals(流流1,流2流)
{
const int的缓冲区大小= 2048;
字节[] =缓冲器1新的字节[缓冲区大小] //缓冲区大小
字节[] =缓冲器2新的字节[缓冲区大小]
而(真){
INT COUNT1 = stream1.Read(缓冲器1,0,缓冲区大小);
INT COUNT2 = stream2.Read(缓冲器2,0,缓冲区大小); 如果(COUNT1!= COUNT2)
返回false; 如果(COUNT1 == 0)
返回true; //你可能会替换为高效memcmp以下
如果(!buffer1.Take(COUNT1).SequenceEqual(buffer2.Take(COUNT2)))
返回false;
}
}
I want to compare two binary files. One of them is already stored on the server with a pre-calculated CRC32 in the database from when I stored it originally.
I know that if the CRC is different, then the files are definitely different. However, if the CRC is the same, I don't know that the files are. So, I'm looking for a nice efficient way of comparing the two streams: one from the posted file and one from the file system.
I'm not an expert on streams, but I'm well aware that I could easily shoot myself in the foot here as far as memory usage is concerned.
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#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!