beta.blog

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 for this entry

  • Sergey

    I have a java code that i need to convert to C#:
    Can someone help me?
    protected static String calculateToken(String key1, String key2) {
    MessageDigest messageDigest = MessageDigest.getInstance(“MD5”);
    messageDigest.update(key1.getBytes());
    messageDigest.update(key2.getBytes());
    String encodedValue=Base64.getEncoder().encodeToString(messageDigest.digest());
    encodedValue = encodedValue.replaceAll(“[\\n]”, “”);
    return encodedValue;
    }

  • mackmans

    md5online.co.uk

Leave a Reply

*

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!