How can I detect in C# whether two files are absolutely identical (size, content, etc.)?
|
|
|
Here's a simple solution, which just reads both files and compares the data. It should be no slower than the hash method, since both methods will have to read the entire file. EDIT As noted by others, this implementation is actually somewhat slower than the hash method, because of its simplicity. See below for a faster method.
You could modify it to read more than one byte at a time, but the internal file stream should already be buffering the data, so even this simple code should be relatively fast. EDIT Thanks for the feedback on speed here. I still maintain that the compare-all-bytes method can be just as fast as the MD5 method, since both methods have to read the entire file. I would suspect (but don't know for sure) that once the files have been read, the compare-all-bytes method requires less actual computation. In any case, I duplicated your performance observations for my initial implementation, but when I added some simple buffering, the compare-all-bytes method was just as fast. Below is the buffering implementation, feel free to comment further! EDIT Jon B makes another good point: in the case where the files actually are different, this method can stop as soon as it finds the first different byte, whereas the hash method has to read the entirety of both files in every case.
|
|||||
|
|
Or you can compare the two files byte-for-byte.... |
|||||
|