How do I create an MD5 hash digest from a text file?
c#, hash, md5
Solution
Here's the routine I'm currently using.
using System.Security.Cryptography;
public string HashFile(string filePath)
{
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
return HashFile(fs);
}
}
public string HashFile( FileStream stream )
{
StringBuilder sb = new StringBuilder();
if( stream != null )
{
stream.Seek( 0, SeekOrigin.Begin );
MD5 md5 = MD5CryptoServiceProvider.Create();
byte[] hash = md5.ComputeHash( stream );
foreach( byte b in hash )
sb.Append( b.ToString( "x2" ) );
stream.Seek( 0, SeekOrigin.Begin );
}
return sb.ToString();
}
Problem
Using C#, I want to create an MD5 hash of a text file. How can I accomplish this? Update: Thanks to everyone for their help. I've finally settled upon the following code - ``` // Create an MD5 hash digest of a file public string MD5HashFile(string fn) { byte[] hash = MD5.Create().ComputeHash(File.ReadAllBytes(fn)); return BitConverter.ToString(hash).Replace("-", ""); } ```