C# - How to hash MD5 for more than one file at the same time?

1.2k views Asked by At

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();
    }
2

There are 2 answers

0
Michael On

If you are attempting to hash multiple files concurrently (via threads), you should take a look at the System.Threading.Tasksnamespace, a part of the Task Parallel Library addition to the .NET Framework - specifically 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. You can create an event handler to pass the results of the MD5 hash calculation when each finishes.

0
User1234 On

Call this method as much as you need... If you asking about hashing all files in the same folder - first get them and run all over them

Directory.GetFiles(dirPath)