Skip to main content

C# helper utility to quickly generate hashes (MD5) for files.

using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Security.Cryptography;
using System.Text;

internal static class HasherNamespace
{
    private readonly static MD5 _hasher;

    static HashUtility()
    {
        _hasher = MD5.Create();
    }

    [SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "By design")]
    internal static string GetHashStringForFile(string filePath)
    {
        string lower;

        using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        {
            byte[] numArray = _hasher.ComputeHash(fs);

            int size = numArray.Length;
            var sb = new StringBuilder(size);

            for (int i = 0; i < size; i++)
            {
                sb.Append(numArray[i].ToString("X2", CultureInfo.InvariantCulture));
            }

            lower = sb.ToString().ToLower(CultureInfo.InvariantCulture);
        }

        return lower;
    }
}