Calculate MD5 Checksum for a File using C#

Snippet to calculate MD5 checksum for a file so you can compare two files for uniqueness or verify that a download had not been altered.

By Tim Trott | C# ASP.Net MVC | January 25, 2009

This is a 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.

C#
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.

C#
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:

C#
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);
Was this article helpful to you?
 

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

If you enjoyed reading this article, or it helped you in some way, all I ask in return is you leave a comment below or share this page with your friends. Thank you.

This post has 18 comment(s). Why not join the discussion!

We respect your privacy, and will not make your email public. Learn how your comment data is processed.

  1. AZ

    On Wednesday 20th of November 2019, ali zaidi said

    Guys how to calculate Md5 in a hex file from a starting address 0x00000 to and end address 0x1FFFF ?

  2. FA

    On Tuesday 8th of May 2012, Farhan said

    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.

  3. HA

    On Tuesday 10th of April 2012, Hitesh Aneja said

    Thanks. It helped a lot.

    Thanks to BitConverter guy as well.

  4. SA

    On Tuesday 28th of February 2012, Saumen said

    grt tutorial.

  5. KA

    On Thursday 26th of January 2012, Karl said

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

  6. NI

    On Thursday 3rd of November 2011, Nick said

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

    string checksum = BitConverter.ToString(retVal);

  7. On Thursday 11th of August 2011, said

    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

  8. AT

    On Friday 8th of July 2011, Aleksandar Toplek said

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

  9. SO

    On Tuesday 7th of June 2011, Soljenitin said

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

  10. JI

    On Sunday 17th of April 2011, jim said

    Perfect. Thanks a lot!

  11. DE

    On Monday 21st of February 2011, Deep said

    C#
    / 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());
                }
            }
        }
    
    }
  12. SC

    On Sunday 2nd of January 2011, scotru said

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

  13. GP

    On Sunday 14th of November 2010, Gaurav Pandey said

    @varsha: Responding late but it may help someone :)

    C#
    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);
        }
    }
  14. On Thursday 18th of March 2010, said

    C#
    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
        }
    }
  15. VA

    On Wednesday 3rd of March 2010, varsha said

    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

  16. FI

    On Friday 26th of February 2010, Finster said

    Great snippet - cheers.

  17. AT

    On Wednesday 3rd of February 2010, Anders Tornes said

    Thank you. Very usefull.

  18. SE

    On Sunday 26th of July 2009, Sensi said

    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.