user960567 user960567 - 2 months ago 7
C# Question

Calculate the Hash of the Contents of a File in C#?

I need to calculate the Hash of the Contents of a File in C#? So, that I can compare two file hashes in my app. I have search but not found.

Answer

You could use MD5CryptoServiceProvider, which will work with text based files as well as binary files.

byte[] myFileData = File.ReadAllBytes(myFileName);
byte[] myHash = MD5.Create().ComputeHash(myFileData);

Or... if you work with large files and do not want to load the whole file into memory:

byte[] myHash;
using (var md5 = MD5.Create())
using (var stream = File.OpenRead(myFileName))
    myHash = md5.ComputeHash(stream);

You can compare to byte arrays from two files with Enumerable.SequenceEqual:

myHash1.SequenceEqual(myHash2); 

You could also try to create an CRC-calculator. See: http://damieng.com/blog/2006/08/08/calculating_crc32_in_c_and_net

Comments