在 C# 中计算文件内容的哈希?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16318087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calculate the Hash of the Contents of a File in C#?
提问by user960567
I need to calculate the Hash of the Contents of a File in C#? So, that I can compare two file hashes in my app. I have search but not found.
我需要在 C# 中计算文件内容的哈希值吗?所以,我可以在我的应用程序中比较两个文件哈希。我有搜索但没有找到。
采纳答案by Martin Mulder
You could use MD5CryptoServiceProvider, which will work with text based files as well as binary files.
您可以使用MD5CryptoServiceProvider, 它将适用于基于文本的文件以及二进制文件。
byte[] myFileData = File.ReadAllBytes(myFileName);
byte[] myHash = MD5.Create().ComputeHash(myFileData);
Or... if you work with large files and do not want to load the whole file into memory:
或者...如果您处理大文件并且不想将整个文件加载到内存中:
byte[] myHash;
using (var md5 = MD5.Create())
using (var stream = File.OpenRead(myFileName))
myHash = md5.ComputeHash(stream);
You can compare to byte arrays from two files with Enumerable.SequenceEqual:
您可以使用Enumerable.SequenceEqual以下命令与两个文件中的字节数组进行比较:
myHash1.SequenceEqual(myHash2);
You could also try to create an CRC-calculator. See: http://damieng.com/blog/2006/08/08/calculating_crc32_in_c_and_net
您也可以尝试创建一个 CRC 计算器。见:http: //damieng.com/blog/2006/08/08/calculating_crc32_in_c_and_net
回答by Shankar Damodaran
You should search better ;)
你应该更好地搜索;)
using System.IO;
using System.Text;
using System.Security.Cryptography;
protected string GetMD5HashFromFile(string fileName)
{
FileStream file = new FileStream(fileName, 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();
}
Pass your file to this function like this.
像这样将您的文件传递给这个函数。
GetMD5HashFromFile("text1.txt");
GetMD5HashFromFile("text2.txt");

