Calculate file checksum in C#

checksum or hash sum is a fixed-size datum computed from an arbitrary block of digital data for the purpose of detecting accidental errors that may have been introduced during its transmission or storage. The integrity of the data can be checked at any later time by recomputing the checksum and comparing it with the stored one. If the checksums match, the data were almost certainly not altered (either intentionally or unintentionally).

The procedure that yields the checksum from the data is called a checksum function or checksum algorithm. A good checksum algorithm will yield a different result with high probability when the data is accidentally corrupted; if the checksums match, the data is very likely to be free of accidental errors.
C#.NET can calculate file checksum by different algorithms, the below class contains two methods, first method calculate MD5 and second calculate SHA1 of file:
using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;

class HashingCompute
{
    public static String GetMD5HashFromFile(String fileName)
    {
        FileStream file = new FileStream(fileName, FileMode.Open);
        MD5 md5 = new MD5CryptoServiceProvider();
        byte[] retVal = md5.ComputeHash(file);
        file.Close();

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < retVal.Length; i++)
        {
            sb.Append(retVal[i].ToString("x2"));
        }
        return sb.ToString();
    }
    public static String GetSHA1HashFromFile(String fileName)    {
        FileStream file = new FileStream(fileName, FileMode.Open);
        SHA1 sha1 = new SHA1CryptoServiceProvider();
        byte[] retVal = sha1.ComputeHash(file);
        file.Close();

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < retVal.Length; i++)
        {
            sb.Append(retVal[i].ToString("x2"));
        }
        return sb.ToString();
    }

}

Davoud Teimouri

Davoud Teimouri is as a professional blogger, vExpert 2015/2016/2017/2018/2019, VCA, MCITP. This blog is started with simple posts and now, it has large following readers.

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newsletter and join other subscribers

Holler Box