ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

GetMD5

Gets the MD5 value of a given file.

Source

using System.IO;
using System.Security.Cryptography;

public static class MyExtensions
{
	/// <summary>
	/// Read and get MD5 hash value of any given filename.
	/// </summary>
	/// <param name="filename">full path and filename</param>
	/// <returns>lowercase MD5 hash value</returns>
	public static string GetMD5(this string filename)
	{
		string result = string.Empty;
		string hashData;

		FileStream fileStream;
		MD5CryptoServiceProvider md5Provider = new MD5CryptoServiceProvider();

		try
		{
			fileStream = GetFileStream(filename);
			byte[] arrByteHashValue = md5Provider.ComputeHash(fileStream);
			fileStream.Close();

			hashData = BitConverter.ToString(arrByteHashValue).Replace("-", "");
			result = hashData;
		}
		catch (Exception ex)
		{
			// Console.WriteLine(ex.Message);
		}

		return (result.ToLower());
	}

	private static FileStream GetFileStream(string pathName)
	{
		return (new FileStream(pathName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
	}
}

Example

string file = @"C:\Temp\filename.txt";
Console.WriteLine("MD5 Hash is: {0}.", file.GetMD5());

Author: Earljon Hidalgo

Submitted on: 26 mrt. 2008

Language: C#

Type: System.String

Views: 8162