C3rd
MD5 File Hash for C# and PHP
Posted: 14 Aug 2016, 10:06am - SundayI encountered again on how to generate MD5 File Hash in C# and compare generated C# file hash to PHP md5_file() function. This is to make sure the file integrity are maintained on copying files. It took me while to find the function but I know I have created one of my previous projects. And this time, I will post here in my blog for future use. Hehehe! For C#:
public static string md5_file(string fileName) { FileStream file = new FileStream(fileName, FileMode.Open); MD5 md5 = new MD5CryptoServiceProvider(); int length = (int)file.Length; // get file length byte[] buffer = new byte[length]; // create buffer int count; // actual number of bytes read int sum = 0; // total number of bytes read // read until Read method returns 0 (end of the stream has been reached) while ((count = file.Read(buffer, sum, length - sum)) > 0) sum += count; // sum is a buffer offset for next reading byte[] retVal = md5.ComputeHash(buffer); file.Close(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString("x2")); } return sb.ToString(); }For PHP:
<?php echo md5_file($filename_with_fullpath); ?>Hope this helps... Thanks to: http://stackoverflow.com/questions/15705676/different-md5-file-hash-in-c-sharp-and-php