Friday, March 8, 2013

How to Get MD5 hash value of a file using CSharp (C#)

When transferring a file through internet there is no guarantee that the file will be secured till it reach the receiver. It may be attacked by any virus or hacker. So the receiver should ensure whether the received file is secured or it attacked. To ensure that before transfer the file we have to get the MD5 hash value of the file. Then after receiving that file the receiver should get the MD5 hash value. If the both hash value is same means the file is secured one. Else it’s an attacked one.
Below is the CSharp code to find the MD5 hash value of a file,
public string GetMD5HashOfAFile(string file)  
{  
    MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();  
    FileStream stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, 8192);  
    md5.ComputeHash(stream);  
    stream.Close();  

    byte[] hash = md5.Hash;  
    StringBuilder sb = new StringBuilder(); 
 
    foreach (byte b in hash)  
    {  
        sb.Append(string.Format("{0:X2}", b));  
    }  

    return sb.ToString();  
}  

1 comment:

  1. The second half of you method can be simplified to:

    return BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", "")

    Optionally add a .ToLower() to the end of that to get:

    return BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", "").ToLower()

    ReplyDelete