[英]C# - How to hash MD5 for more than one file at the same time?
I am trying to make an MD5 hasher and with the help of online tutorials I managed to make something that works. 我正在尝试制作MD5散列器,并在在线教程的帮助下设法做出了一些有用的事情。 However, I can't figure out how to make the code work for more than just one file.
但是,我无法弄清楚如何使代码能用于多个文件。
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
string filePath = e.Argument.ToString();
byte[] buffer;
int bytesRead;
long size;
long totalBytesRead = 0;
using (Stream file = File.OpenRead(filePath))
{
size = file.Length;
using (HashAlgorithm hasher = MD5.Create())
{
do
{
buffer = new byte[4096];
bytesRead = file.Read(buffer, 0, buffer.Length);
totalBytesRead += bytesRead;
hasher.TransformBlock(buffer, 0, bytesRead, null, 0);
backgroundWorker1.ReportProgress((int)((double)totalBytesRead / size * 100));
}
while (bytesRead != 0);
hasher.TransformFinalBlock(buffer, 0, 0);
e.Result = MakeHashString(hasher.Hash);
}
}
}
private static string MakeHashString(byte[] hashBytes)
{
StringBuilder hash = new StringBuilder(32);
foreach (byte b in hashBytes)
hash.Append(b.ToString("X2").ToLower());
return hash.ToString();
}
尽可能多地调用此方法...如果您要求对同一文件夹中的所有文件进行哈希处理-首先获取它们并遍历它们
Directory.GetFiles(dirPath)
If you are attempting to hash multiple files concurrently (via threads), you should take a look at the System.Threading.Tasks
namespace, a part of the Task Parallel Library addition to the .NET Framework - specifically Parallel.ForEach
. 如果尝试同时(通过线程)对多个文件进行哈希处理,则应查看
System.Threading.Tasks
命名空间,它是.NET Framework任务并行库的一部分,特别是Parallel.ForEach
。
Microsoft provides a good example of how to work with multiple files concurrently via How to: Write a Simple Parallel.ForEach Loop available via MSDN. Microsoft提供了一个很好的示例,说明如何通过“ 如何:编写简单的Parallel.ForEach循环”(可通过MSDN获得)并发处理多个文件。 You can create an event handler to pass the results of the MD5 hash calculation when each finishes.
您可以创建一个事件处理程序,以在每次完成时传递MD5哈希计算的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.