Web Design that taps into the haromny and vision of your dreams.

Calculate MD5 Checksum for a File using C#

Calculate MD5 checksums for files and validate checksums

Written By on in C#

216 words, estimated reading time 1 minutes.

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

Last updated on: Wednesday 21st June 2017

 

Comments
Farhan

Farhan

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 to Farhan
Hitesh Aneja

Hitesh Aneja

Thanks. It helped a lot.

Thanks to BitConverter guy as well.

Reply to Hitesh Aneja
Saumen

Saumen

grt tutorial.

Reply to Saumen
Karl

Karl

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

Reply to Karl
Nick

Nick

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

string checksum = BitConverter.ToString(retVal);

Reply to Nick

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 to
Aleksandar Toplek

Aleksandar Toplek

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

Reply to Aleksandar Toplek
Soljenitin

Soljenitin

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

Reply to Soljenitin
jim

jim

Perfect. Thanks a lot!

Reply to jim
Deep

Deep

// 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 to Deep
scotru

scotru

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

Reply to scotru
Gaurav Pandey

Gaurav Pandey

@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 to Gaurav Pandey

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 to
varsha

varsha

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 to varsha
Finster

Finster

Great snippet - cheers.

Reply to Finster
Anders Tornes

Anders Tornes

Thank you. Very usefull.

Reply to Anders Tornes
Sensi

Sensi

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 to Sensi

 

Leave a Reply

Your email address will not be published.





If you find something abusive or that does not comply with our terms or guidelines please flag it as inappropriate.

Copyright © 2001-2018 Tim Trott, all rights reserved. Web Design by Azulia Designs

This web page is licensed for your personal, private, non-commercial use only.

Disclaimer, Privacy & LegalSitemapContact Me