代码
/// <summary> /// 原文链接:https://blog.csdn.net/makenothing/article/details/39493779 /// </summary> /// <param name="fileName"></param> /// <returns></returns> /// <exception cref="Exception"></exception> private static string GetMD5HashFromFile(string fileName) { try { FileStream file = new FileStream(fileName, FileMode.Open); System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] retVal = md5.ComputeHash(file); file.Close(); 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("GetMD5HashFromFile() fail,error:" + ex.Message); } }
选择文件
private void btnSelectFile1_Click(object sender, EventArgs e) { using (OpenFileDialog openFileDialog = new OpenFileDialog()) { openFileDialog.InitialDirectory = "C:\\Users\\jay.star\\Desktop"; // 初始目录 openFileDialog.Title = "选择文件"; // 对话框标题 openFileDialog.Filter = "所有文件(*.*)|*.*"; // 文件过滤器 if (openFileDialog.ShowDialog() == DialogResult.OK) { // 获取文件路径 string filePath = openFileDialog.FileName; var md5Str = GetMD5HashFromFile(filePath); txtFile1.Text = md5Str; } } }
浙公网安备 33010602011771号