How should I compute files hash(md5 & SHA1) in C#

n1kita picture n1kita · Nov 26, 2012 · Viewed 31.4k times · Source

This is my first C# project and I'm almost newbie. I use openfiledialoge for selecting file and get the filepath by GetFullPath method and store it in a variable called for example fpath. I need to calculate the hash of the file that its path is stored in fpath variable.I think it can be done via GetHashCode. Can anybody give me a snippet or a little guide?

Answer

Saddam Abu Ghaida picture Saddam Abu Ghaida · Nov 26, 2012
using (FileStream stream = File.OpenRead(file))
{
    SHA256Managed sha = new SHA256Managed();
    byte[] hash = sha.ComputeHash(stream);
    return BitConverter.ToString(hash).Replace("-", String.Empty);
}