Calculate MD5 Checksum for a File using C#

Written by on Sunday 25th January 2009 under C#

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);

17 Responses to “Calculate MD5 Checksum for a File using C#”

  1. Sensisays:

    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.

  2. Anders Tornessays:

    Thank you. Very usefull.

  3. Finstersays:

    Great snippet - cheers.

  4. varshasays:

    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

  5. Anonymoussays:

    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
    }
    }

  6. Gaurav Pandeysays:

    @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);
    }
    }

  7. scotrusays:

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

  8. Deepsays:

    // 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());
    }
    }
    }

    }

  9. jimsays:

    Perfect. Thanks a lot!

  10. Soljenitinsays:

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

  11. Aleksandar Topleksays:

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

  12. Anonymoussays:

    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

  13. Nicksays:

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

    string checksum = BitConverter.ToString(retVal);

  14. Karlsays:

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

  15. Saumensays:

    grt tutorial.

  16. Hitesh Anejasays:

    Thanks. It helped a lot.

    Thanks to BitConverter guy as well.

  17. Farhansays:

    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.

Leave a Reply