Hash Large Files with .Net SHA1/MD5

I've been working on an application that checks for duplicate files.  One of the better ways to test whether files are identical is to hash them.  MD5 hashing is common, but it has been known to cause collisions.  I elected to use the SHA1 algorithm instead.

In my testing, I've found that I can has a ~1GB file within about 7 seconds without consuming an equal share of memory.

You will need the following namespaces:

  • System.Security.Cryptography
  • System.IO

SHA1 Hash Example Code:

public string SHA1HashFile(string sPath)
{
    string sHash = "";

    using (StreamReader sr = new StreamReader(sPath))
    {

        SHA1CryptoServiceProvider sha1h = new SHA1CryptoServiceProvider();
        sHash = BitConverter.ToString(sha1h.ComputeHash(sr.BaseStream));

    }

    return sHash;
}

Usage: SHA1HashFile("C:\\Path\\File.iso");

MD5 Hash Example Code:

public string MD5HashFile(string sPath)
{


    string sHash = "";

    using (StreamReader sr = new StreamReader(sPath))
    {

        MD5CryptoServiceProvider md5h = new MD5CryptoServiceProvider();
        sHash = BitConverter.ToString(md5h.ComputeHash(sr.BaseStream));

     }

    return sHash;
}

Usage: MD5HashFile("C:\\Path\\File.iso");

Your rating: None Average: 3.9 (8 votes)