tags:

views:

254

answers:

3

Using C#, I want to create an MD5 hash of a text file. How can I accomplish this? Please include code. Many thanks!

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("-", "");            
    }
+1  A: 

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();
    }
roufamatic
That's perfect roufamatic. Does it return a 32 digit hex?
CraigS
@CraigS: ask (or read) the code... ;)
Lucero
It returns a string of hex.
roufamatic
Thanks roufamatic.
CraigS
Just tested the function out, and it does exactly what I need - many thanks again.
CraigS
If you don't need to reuse the stream you can of course remove all that code. This used to be in a pipeline of sorts so that the stream could be hashed first, then gzipped. Now I mostly just care about the hash, hence the shortcut.
roufamatic
+1  A: 

Here is a one liner

http://snippets.dzone.com/posts/show/2771

StingyJack
Sorry - I can't open that site. Can you include the 1 liner here? Many thanks!
CraigS
Got it - string hash = Convert.ToBase64String(new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(System.Text.Encoding.Default.GetBytes(SomeString)));
CraigS
+1  A: 

Short and to the point. filename is your text file's name:

BitConverter.ToString(MD5.Create().ComputeHash(File.ReadAllBytes(filename)))
Jesse C. Slicer
ToBase64String doesn't return what I want. However, BitConverter.ToString around the byte array does the trick
CraigS