下載軟件后使用c#獲取文件的md5碼示例
很多朋友在下載文件的時候,經(jīng)常會發(fā)現(xiàn)網(wǎng)站提供了MD5校驗碼,其實這個MD5碼的作用就是當你下載文件好了之后,拿你下載好的文件的MD5校驗碼,跟下載網(wǎng)站提供的進行比較,如果完全一致,說明你下載中文件沒問題,如果校驗碼不一致,說明下載過程中你的文件出錯了,或者是你的文件下載出錯了,反正就是跟原始文件不一致。而且只要是文件不一樣,MD5碼肯定不一樣,這個是不會重復的,那么到底如何獲取文件的MD5碼呢?下面就使用C#代碼進行講解。
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Security;
using System.Security.Cryptography;
using System.IO;
namespace MD5FileForm
{
public partial class MD5Form : Form
{
public MD5Form()
{
InitializeComponent();
}
private void btnGetMD5_Click(object sender, EventArgs e)
{
MD5 md5 = MD5.Create();
OpenFileDialog ofd = new OpenFileDialog();
ofd.ShowDialog();
FileStream fs = new FileStream(ofd.FileName, FileMode.Open);
byte[] bs = md5.ComputeHash(fs);
//獲取到MD5碼
string md5Str = BitConverter.ToString(bs).Replace("-","");
MessageBox.Show(string.Format("[{0}]的MD5碼為:\n{1}",ofd.FileName,md5Str));
}
}
}
第二個使用示例
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace Test
{
public class MD5Code
{
/// <summary>
/// 獲取文件的MD5碼
/// </summary>
/// <param name="fileName">傳入的文件名(含路徑及后綴名)</param>
/// <returns></returns>
public string GetMD5HashFromFile(string fileName)
{
try
{
FileStream file = new FileStream(fileName, System.IO.FileMode.Open);
MD5 md5 = new 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);
}
}
}
}
相關文章
C#優(yōu)雅的實現(xiàn)INotifyPropertyChanged接口
這篇文章介紹了C#實現(xiàn)INotifyPropertyChanged接口的方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-08-08c# wpf使用GMap.NET類庫,實現(xiàn)地圖軌跡回放
這篇文章主要介紹了c# wpf使用GMap.NET類庫,實現(xiàn)地圖軌跡回放的方法,幫助大家更好的理解和學習使用c#,感興趣的朋友可以了解下2021-03-03