I am trying to make an MD5 hasher and with the help of online tutorials I managed to make something that works. 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();
}
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 - specificallyParallel.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. You can create an event handler to pass the results of the MD5 hash calculation when each finishes.