比较C#中的二进制文件

Sim*_*row 31 c# compare file

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

我知道如果CRC不同,那么文件肯定是不同的.但是,如果CRC是相同的,我不知道文件是什么.所以,我正在寻找一种比较两个流的有效方法:一个来自发布的文件,另一个来自文件系统.

我不是溪流的专家,但我很清楚,就内存使用而言,我可以轻松地在这里拍摄自己.

Meh*_*ari 43

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 要求conunt1 == count2可能不准确,因为Stream.Read可以自由返回长度小于请求的字节数的块.见http://msdn.microsoft.com/en-us/library/vstudio/system.io.stream.read(v=vs.100).aspx (5认同)
  • @Karata是绝对正确的,这个错误的代码不应该没有修正(有人可能会在我以后使用的软件上使用它).至少`FileStreamEquals`应该采用两个正确类型的`FileStream`参数; a*weak*case*****************************************************************但是你会在每一个意外事件上打赌你的生活(或你的公司)吗?网络映射驱动器怎么样?命名管道? (2认同)

Lar*_*ars 20

我通过在读取流块上的循环中使用Int64比较来加速"memcmp".这减少了约1/4的时间.

    private static bool StreamsContentsAreEqual(Stream stream1, Stream stream2)
    {
        const int bufferSize = 2048 * 2;
        var buffer1 = new byte[bufferSize];
        var 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;
            }

            int iterations = (int)Math.Ceiling((double)count1 / sizeof(Int64));
            for (int i = 0; i < iterations; i++)
            {
                if (BitConverter.ToInt64(buffer1, i * sizeof(Int64)) != BitConverter.ToInt64(buffer2, i * sizeof(Int64)))
                {
                    return false;
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)


小智 7

如果你不想依赖crc,我会怎么做:

    /// <summary>
    /// Binary comparison of two files
    /// </summary>
    /// <param name="fileName1">the file to compare</param>
    /// <param name="fileName2">the other file to compare</param>
    /// <returns>a value indicateing weather the file are identical</returns>
    public static bool CompareFiles(string fileName1, string fileName2)
    {
        FileInfo info1 = new FileInfo(fileName1);
        FileInfo info2 = new FileInfo(fileName2);
        bool same = info1.Length == info2.Length;
        if (same)
        {
            using (FileStream fs1 = info1.OpenRead())
            using (FileStream fs2 = info2.OpenRead())
            using (BufferedStream bs1 = new BufferedStream(fs1))
            using (BufferedStream bs2 = new BufferedStream(fs2))
            {
                for (long i = 0; i < info1.Length; i++)
                {
                    if (bs1.ReadByte() != bs2.ReadByte())
                    {
                        same = false;
                        break;
                    }
                }
            }
        }

        return same;
    }
Run Code Online (Sandbox Code Playgroud)


Lar*_*rry 6

接受的答案有一个错误已被指出,但从未纠正:流读取调用不能保证返回请求的所有字节。

BinaryReader ReadBytes调用保证返回请求的字节数,除非首先到达流的末尾。

以下代码利用BinaryReader进行比较:

    static private bool FileEquals(string file1, string file2)
    {
        using (FileStream s1 = new FileStream(file1, FileMode.Open, FileAccess.Read, FileShare.Read))
        using (FileStream s2 = new FileStream(file2, FileMode.Open, FileAccess.Read, FileShare.Read))
        using (BinaryReader b1 = new BinaryReader(s1))
        using (BinaryReader b2 = new BinaryReader(s2))
        {
            while (true)
            {
                byte[] data1 = b1.ReadBytes(64 * 1024);
                byte[] data2 = b2.ReadBytes(64 * 1024);
                if (data1.Length != data2.Length)
                    return false;
                if (data1.Length == 0)
                    return true;
                if (!data1.SequenceEqual(data2))
                    return false;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)