您的位置:首页 > 编程语言 > C#

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