c# 如何给文件计算MD5
2014-07-25 15:51
295 查看
在项目中,当我们需要把数据文件上传到ftp时,为了保证数据的完整性,我们会计算数据文件的MD5,并把MD5文件和数据文件一同上传。
那么如何产生数据文件的MD5呢?
我们可以通过System.Security.Cryptography.MD5类和System.BitConverter类来实现:
private void WriteMD5(string zipFile, string ctrlFile)
{
// Add hash code to ctrl file
byte[] validHash = GenerateMD5Hash(zipFile);
// make sure that we add hash value in a new line
bool addNewLine = false;
using (StreamReader sr = new StreamReader(ctrlFile))
{
string[] lines = sr.ReadToEnd().Split(new char[] { '\n' });
if (lines.Length == 1) addNewLine = true;
}
// ready to put the control file, so add the hash string to it
using (StreamWriter sw = new StreamWriter(ctrlFile, true))
{
if (addNewLine) sw.WriteLine("");
sw.WriteLine(BitConverter.ToString(validHash).Replace("-", ""));
}
}
private byte[] GenerateMD5Hash(string localFileName)
{
byte[] localHash = null;
using (MD5 md5Hash = MD5.Create())
{
using (FileStream localFile = File.OpenRead(localFileName))
{
localHash = md5Hash.ComputeHash(localFile);
}
}
return localHash;
}
那么如何产生数据文件的MD5呢?
我们可以通过System.Security.Cryptography.MD5类和System.BitConverter类来实现:
private void WriteMD5(string zipFile, string ctrlFile)
{
// Add hash code to ctrl file
byte[] validHash = GenerateMD5Hash(zipFile);
// make sure that we add hash value in a new line
bool addNewLine = false;
using (StreamReader sr = new StreamReader(ctrlFile))
{
string[] lines = sr.ReadToEnd().Split(new char[] { '\n' });
if (lines.Length == 1) addNewLine = true;
}
// ready to put the control file, so add the hash string to it
using (StreamWriter sw = new StreamWriter(ctrlFile, true))
{
if (addNewLine) sw.WriteLine("");
sw.WriteLine(BitConverter.ToString(validHash).Replace("-", ""));
}
}
private byte[] GenerateMD5Hash(string localFileName)
{
byte[] localHash = null;
using (MD5 md5Hash = MD5.Create())
{
using (FileStream localFile = File.OpenRead(localFileName))
{
localHash = md5Hash.ComputeHash(localFile);
}
}
return localHash;
}
相关文章推荐
- c# 如何给文件计算MD5
- [C#] 计算大文件的MD5的两种方式(直接调用方法计算,流计算-适用于大文件)
- python里如何计算大文件的md5
- C# 计算文件MD5
- C#计算大文件MD5(同步)
- C# 计算字符串/文件的哈希值(MD5、SHA)
- C#遍历文件夹下所有文件通过MD5函数计算文件的MD5
- 如何计算文件MD5 sha1 -- 微软MD5/SHA1 校验工具 Microsoft File Checksum Integrity Verifier
- 如何有效的使用C#读取文件
- c#中字符串MD5的计算方法
- 如何有效的使用C#读取文件
- 如何用C#获得文件信息以及扩展信息
- 如何用C#获得文件信息以及扩展信息
- 创建一个强名称密钥文件+ 如何在 Visual C# .NET 中将程序集安装到全局程序集缓存中
- 如何计算 一个音视频文件 (.ts)文件 (包含pcr信息). 播放所使用的带宽
- [C#]如何将类放置于不同的文件中在同一个解决方案中调用?(不同解决方案的需要使用类库ClassLibrary)
- [C#]如何将类放置于不同的文件中在同一个解决方案中调用?(不同解决方案的需要使用类库ClassLibrary)
- 如何有效地使用C#读取文件
- [愚翁专栏]如何用C#获得文件信息以及扩展信息
- 如何在 Visual C# .NET 中执行基本的文件 I/O