How to Calculate MD5 checksum for a file in C# ?

There are times when you want to calculate MD5 checksum for a file in C# and you can easily do that using System.Security.Cryptography.MD5

You can use the ComputeHash method of the MD5 instance by passing the stream. You can later it to Hex using the BitConverter so that you can represent it as string for conversion.

How to Calculate MD5 checksum for a file in C# ?

Below is a sample code snippet demonstrating a method that accepts the file name along with the path and returns the calculated checksum.

using (var md5Instance = MD5.Create())
{
	using (var stream = File.OpenRead(filename))
	{
		var hashResult = md5Instance.ComputeHash(stream);
		return BitConverter.ToString(hashResult).Replace("-", "").ToLowerInvariant();
	}
}