Code to determine a file hash. It returns an unique id from a file. The idea is to read the file in binary mode and calculate an MD5 hash.
md5 calculation (source)
protected internal string MD5HashString(string sTextToHash)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] byValue;
byte[] byHash;
// Neues CryptoServiceProvider Objekt erzeugen
byValue = System.Text.Encoding.UTF8.GetBytes(sTextToHash);
// Berechne den Hash und schreibe ein Array von Bytes zurück
byHash = md5.ComputeHash(byValue);
// Provider löschen
md5.Clear();
// Gibt einen Base 64 codierten String mit dem Hashwert zurück
return Convert.ToBase64String(byHash);
}
full example
#region . hashing methods
private static string CalculateHashFromFile(string filename)
{
// hash generation from file
// read file bytes
byte[] bytes = File.ReadAllBytes(filename);
// md5 calculation
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] output = md5.ComputeHash(bytes);
string hash = Convert.ToBase64String(output);
// returning
return hash;
}
#endregion