public static class FileHelper
{
/// <summary>
/// 获取文件MD5值
/// </summary>
/// <param name="fileName">文件绝对路径</param>
/// <returns>MD5值</returns>
public static string GetFileMD5(string fileName)
{
try
{
using (System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
return GetFileMD5(fs);
}
}
catch (Exception ex)
{
throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
}
}
/// <summary>
/// 获取文件MD5值
/// </summary>
/// <param name="fs">文件流</param>
/// <returns>MD5值</returns>
public static string GetFileMD5(FileStream fs)
{
try
{
System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] retVal = md5.ComputeHash(fs);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < retVal.Length; i++)
{
sb.Append(retVal[i].ToString("x2"));
}
return sb.ToString();
}
catch (Exception ex)
{
throw new Exception("生成文件MD5是发生异常:" + ex.Message);
}
}
}