Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare binary files in C#

Tags:

c#

file

compare

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.

like image 679
Simon Farrow Avatar asked Jun 09 '09 08:06

Simon Farrow


People also ask

How do I compare two binary files?

Use the command cmp to check if two files are the same byte by byte. The command cmp does not list differences like the diff command. However it is handy for a fast check of whether two files are the same or not (especially useful for binary data files).

Does diff work on binary files?

You can also force diff to consider all files to be binary files, and report only whether they differ (but not how). Use the `--brief' option for this. In operating systems that distinguish between text and binary files, diff normally reads and writes all data as text.

Can meld compare binary files?

This tool has a nice feature I'm missing a little bit in meld. You can compare binary files like e. g. bitmaps. contain binary data saved by our applications. Would be nice to have this in meld, nevertheless meld is a great tool!

What is binary compare?

A Binary comparison compares the numeric Unicode value of each character in each string. A Text comparison compares each Unicode character based on its lexical meaning in the current culture. In Microsoft Windows, sort order is determined by the code page.


1 Answers

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;     } } 
like image 123
mmx Avatar answered Sep 28 '22 23:09

mmx