Learning never exhausts the mind

By

This is little snippet I have used when validating an important file copy. I compare the original checksum with the destination checksum, both returned from this code sample.

You will need to add System.IO, System.Text and System.Security.Cryptography to your using clause if you haven't done already.

To use, simply pass in a filename and the method will return an MD5 hash string.

protected string GetMD5HashFromFile(string fileName)
{
  using (var md5 = MD5.Create())
  {
    using (var stream = File.OpenRead(filename))
    {
      return BitConverter.ToString(md5.ComputeHash(stream)).Replace("-",string.Empty);
    }
  }
}

You can also use this more advanced hashing function which you can pass in a HashAlgorithm object as a parameter to get a file has for different algorithms.

public static class Algorithms
{
  public static readonly HashAlgorithm MD5 = new MD5CryptoServiceProvider();
  public static readonly HashAlgorithm SHA1 = new SHA1Managed();
  public static readonly HashAlgorithm SHA256 = new SHA256Managed();
  public static readonly HashAlgorithm SHA384 = new SHA384Managed();
  public static readonly HashAlgorithm SHA512 = new SHA512Managed();
  public static readonly HashAlgorithm RIPEMD160 = new RIPEMD160Managed();
}

public static string GetHashFromFile(string fileName, HashAlgorithm algorithm)
{
  using (var stream = new BufferedStream(File.OpenRead(fileName), 100000))
  {
    return BitConverter.ToString(algorithm.ComputeHash(stream)).Replace("-", string.Empty);
  }
}

Usage is as follows:

string checksumMd5 = GetChecksum(path, Algorithms.MD5);
string checksumSha1 = GetChecksum(path, Algorithms.SHA1);
string checksumSha256 = GetChecksum(path, Algorithms.SHA256);
string checksumSha384 = GetChecksum(path, Algorithms.SHA384);
string checksumSha512 = GetChecksum(path, Algorithms.SHA512);
string checksumRipemd160 = GetChecksum(path, Algorithms.RIPEMD160);

 

Did you enjoy this post? Let others know!

If you enjoyed this post, please share it with others. Click one of the social media buttons below to share on Facebook, Twitter, LinkedIn, Pinterest or email to a friend.

17 thoughts on “Calculate MD5 Checksum for a File using C#
  • 8th May 2012 at 12:00 am

    Please let me know how to calculate the cksum of a file in .Net, the output should be equavalent to the cksum command of linux.

    Reply
  • 10th April 2012 at 12:00 am

    Thanks. It helped a lot.

    Thanks to BitConverter guy as well.

    Reply
  • 28th February 2012 at 12:00 am

    grt tutorial.

    Reply
  • 26th January 2012 at 12:00 am

    I need to run the md5 checksum process over an entire file in a rpg program. Is that code available ?

    Reply
  • 3rd November 2011 at 12:00 am

    Instead of using the StringBuilder in a loop, you can use the BitConverter.

    string checksum = BitConverter.ToString(retVal);

    Reply
  • 11th August 2011 at 12:00 am

    This thing fails. Error 1 Cannot implicitly convert type 'System.Security.Cryptography.MD5CryptoServiceProvider' to 'MD5FileHash.MD5' c:usersnickdocumentsvisual studio 2010ProjectsMD5FileHashMD5FileHashMD5.cs 15 23 MD5FileHash
    Error 2 'MD5FileHash.MD5' does not contain a definition for 'ComputeHash' and no extension method 'ComputeHash' accepting a first argument of type 'MD5FileHash.MD5' could be found (are you missing a using directive or an assembly reference?) c:usersnickdocumentsvisual studio 2010ProjectsMD5FileHashMD5FileHashMD5.cs 16 33 MD5FileHash

    Reply
  • Aleksandar Toplek
    8th July 2011 at 12:00 am

    @Anonymous It looks like your solution is better and more compact... thank you!

    Reply
  • 7th June 2011 at 12:00 am

    How to calculate the file MD5 if the file is already open (in use) ?

    Reply
  • 17th April 2011 at 12:00 am

    Perfect. Thanks a lot!

    Reply
  • 21st February 2011 at 12:00 am

    // the following class has a function for entire folders as well as for individual files.

    using System;
    using System.IO;
    using System.Security.Cryptography;
    using System.Text;

    public class Hasher
    {
    MD5 hashAlgo = null;
    StringBuilder sb;
    public Hasher()
    {
    hashAlgo = new MD5CryptoServiceProvider();

    }

    public string getHashOverFolder(String path)
    {
    sb = new StringBuilder();
    getFolderContents(path);
    return sb.ToString().GetHashCode().ToString();
    }

    public string getHashOverFile(String filename)
    {
    sb = new StringBuilder();
    getFileHash(filename);
    return sb.ToString().GetHashCode().ToString();
    }

    private void getFolderContents(string fold)
    {
    foreach (var d in Directory.GetDirectories(fold))
    {
    getFolderContents(d);
    }
    foreach (var f in Directory.GetFiles(fold))
    {
    getFileHash(f);
    }
    }

    private void getFileHash(String f)
    {
    using (FileStream file = new FileStream(f, FileMode.Open, FileAccess.Read))
    {
    byte[] retVal = hashAlgo.ComputeHash(file);
    file.Close();

    foreach (var y in retVal)
    {
    sb.Append(y.ToString());
    }
    }
    }

    }

    Reply
  • 2nd January 2011 at 12:00 am

    Hmmm---I think you are hashing the FileStream object here--rather than the contents of the stream (the file bytes itself)

    Reply
  • 14th November 2010 at 12:00 am

    @varsha: Responding late but it may help someone  :) 
    class Hasher
    {
    static int hasher = -1;
    static MD5 hashAlgo = null;

    static Hasher()
    {
    hashAlgo = new MD5CryptoServiceProvider();
    }

    public static int getHashOverFolder(String path)
    {
    dfs(path);
    return hasher;
    }

    static void dfs(String path)
    {
    foreach (var x in Directory.GetFiles(path))
    {
    using (FileStream file = new FileStream(x, FileMode.Open, FileAccess.Read))
    {
    byte[] retVal = hashAlgo.ComputeHash(file);

    StringBuilder sb = new StringBuilder();
    foreach (var y in retVal)
    sb.Append(y);

    hasher ^= sb.ToString().GetHashCode();
    }
    }

    foreach (var y in Directory.GetDirectories(path))
    dfs(y);
    }
    }

    Reply
  • 18th March 2010 at 12:00 am

    using (MD5 md5 = new MD5CryptoServiceProvider()) {
    using (FileStream file = new FileStream(fileName, FileMode.Open)) {
    byte[] retVal = md5.ComputeHash(file);
    return BitConverter.ToString(retVal).Replace("-", ""); // hex string
    }
    }

    Reply
  • 3rd March 2010 at 12:00 am

    how do i generate the hash code for an entire project. i.e. for a whole directory or full project that contains a set of files

    Reply
  • 26th February 2010 at 12:00 am

    Great snippet - cheers.

    Reply
  • 3rd February 2010 at 12:00 am

    Thank you. Very usefull.

    Reply
  • 26th July 2009 at 12:00 am

    How can I check a checksum of a process that is running and probabely in use like svchost.exe? I know there are programs which can do it.

    Reply

Leave a Reply

Fields marked with * are mandatory.

We respect your privacy, and will not make your email public. Hashed email address may be checked against Gravatar service to retrieve avatars. This site uses Akismet to reduce spam. Learn how your comment data is processed.