user960567 user960567 - 1 month ago 6x
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.


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:


You could also try to create an CRC-calculator. See: