beta.blog

Programming

C# – Compute MD5 Hash of a File

by on Feb.15, 2012, under Programming

The following example code shows how to calculate the MD5 Checksum of a file in C-Sharp:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security.Cryptography;

class Program
{
    static void Main(string[] args)
    {
        if (args.Length <= 0) // No Arguments passed, exit
        {
            Console.WriteLine("Drag and Drop a file onto this exe to get it's MD5 hash.");
            Console.Read();
            return;
        }
        if (File.Exists(args[0]) == false) // Invalid Argument passed, exit
        {
            Console.WriteLine("Drag and Drop a file onto this exe to get it's MD5 hash.");
            Console.Read();
            return;
        }

        Console.WriteLine(GetMD5HashFromFile(args[0])); // Compute MD5 hash
        Console.Read(); // Wait for user input
    }

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

You may also want to use it as a stand alone function:

private static string GetMD5HashFromFile(string fileName)
{
    FileStream file = new FileStream(fileName, FileMode.Open);
    System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.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();
}
2 Comments more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!