在.NET中计算文件的MD5值
更新记录
本文迁移自Panda666原博客,原发布时间:2021年7月2日。
直接上代码吧:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace PandaTestClass
{
class Program
{
///
/// 计算文件的MD5值
///
///
///
public static string GetMD5HashFromFile(string fileName)
{
try
{
//新建文件流
using (FileStream file = new FileStream(fileName, System.IO.FileMode.Open))
{
//MD5加密服务提供器
MD5 md5 = new MD5CryptoServiceProvider();
//对文件进行计算MD5
byte[] retVal = md5.ComputeHash(file);
//保存输出结果
StringBuilder sb = new StringBuilder();
//转为2进制
for (int i = 0; i < retVal.Length; i++)
{
sb.Append(retVal[i].ToString("x2"));
}
return sb.ToString();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
static void Main(string[] args)
{
string filePath = @"E:\SQLServer2019-x64-CHS-Dev.iso";
Console.WriteLine("准备计算");
string md5String = GetMD5HashFromFile(filePath);
Console.WriteLine(md5String);
Console.WriteLine("计算完成");
//wait
Console.WriteLine("Main Suceess");
Console.ReadKey();
}
}
}