下载软件后使用c#获取文件的md5码示例
时间:2022-02-08 21:39:58
很多朋友在下载文件的时候,经常会发现网站提供了MD5校验码,其实这个MD5码的作用就是当你下载文件好了之后,拿你下载好的文件的MD5校验码,跟下载网站提供的进行比较,如果完全一致,说明你下载中文件没问题,如果校验码不一致,说明下载过程中你的文件出错了,或者是你的文件下载出错了,反正就是跟原始文件不一致。而且只要是文件不一样,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);
}
}
}
}
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
java动态绑定和静态绑定用法实例详解
浅谈java项目与javaweb项目导入jar包的区别
VMware虚拟机下hadoop1.x的安装方法
Java SpringSecurity+JWT实现登录认证
Java分页工具类及其使用(示例分享)
springboot vue组件开发实现接口断言功能
![](https://img.aspxhome.com/file/2023/9/61869_0s.gif)
详解Java8如何使用Lambda表达式进行比较
java String的深入理解
![](https://img.aspxhome.com/file/2023/5/69895_0s.png)
Java中实现多线程关键词整理(总结)
mybatis的if判断integer问题
java中类与对象的使用详情
java时间戳转日期格式的实现代码
Unity3D Shader实现贴图切换效果
![](https://img.aspxhome.com/file/2023/9/77229_0s.gif)
在IntelliJ IDEA中多线程并发代码的调试方法详解
![](https://img.aspxhome.com/file/2023/6/67146_0s.jpg)
slf4j与jul、log4j1、log4j2、logback的集成原理
![](https://img.aspxhome.com/file/2023/2/68552_0s.png)
Java发送报文与接收报文的实例代码
深入了解Hadoop如何实现序列化
![](https://img.aspxhome.com/file/2023/8/62348_0s.png)
Java 线程对比(Thread,Runnable,Callable)实例详解
![](https://img.aspxhome.com/file/2023/5/75765_0s.png)
C#4.0新特性之协变与逆变实例分析
springboot+jersey+tomcat实现跨域方式上传文件到服务器的方式
![](https://img.aspxhome.com/file/2023/9/66679_0s.jpg)