代碼
/// <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 = "選擇文件"; // 對(duì)話(huà)框標(biāo)題 openFileDialog.Filter = "所有文件(*.*)|*.*"; // 文件過(guò)濾器 if (openFileDialog.ShowDialog() == DialogResult.OK) { // 獲取文件路徑 string filePath = openFileDialog.FileName; var md5Str = GetMD5HashFromFile(filePath); txtFile1.Text = md5Str; } } }
浙公網(wǎng)安備 33010602011771號(hào)