计算C#中文件内容的哈希值? [英] Calculate the Hash of the Contents of a File in C#?
问题描述
我需要计算C#中文件内容的哈希值吗?因此,我可以在我的应用程序中比较两个文件哈希.我有搜索但没有找到.
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.
推荐答案
您可以使用 MD5CryptoServiceProvider
,它将与基于文本的文件以及二进制文件一起使用.
You could use MD5CryptoServiceProvider
, which will work with text based files as well as binary files.
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);
您可以使用 Enumerable.SequenceEqual
与两个文件的字节数组进行比较:
You can compare to byte arrays from two files with Enumerable.SequenceEqual
:
myHash1.SequenceEqual(myHash2);
您还可以尝试创建CRC计算器.请参阅: http://damieng.com/blog/2006/08/08/calculating_crc32_in_c_and_net
You could also try to create an CRC-calculator. See: http://damieng.com/blog/2006/08/08/calculating_crc32_in_c_and_net
这篇关于计算C#中文件内容的哈希值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!