Search code examples
c#progress-barbackgroundworkerstatus

How to monitor status while hashing a file?


I'm building a small app that calculate hash from any given file to multiple types of hashing algorithm.

For simplicity sake I will focus on only 1 algorithm which is processor intensive and even if file is around 15mb it takes about half a minute to calculate the hash.

I am running the calculation by using BackgroundWorker (I'm not sure if that a right approach for a calculation but I'm just experimenting).

Now, I want to have a progress bar which will display hashing progess but I don't know how to get the maximum value needed nor where to put DoStep method.

Any ideas?

My code:

private void btnBrowse_Click(object sender, EventArgs e)
{
    ofdBrowse.Filter = "All Files|*.*";
    ofdBrowse.Title = "Open file.";

    if (ofdBrowse.ShowDialog() == DialogResult.OK)
    {
        txtPath.Text = ofdBrowse.FileName;

        bwWorker.RunWorkerAsync();
    }
}

private void bwWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    t5 = hash.HashSHA512(txtPath.Text);
}

void bwWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    txtSHA512.Text = t5;
}

Solution

  • In order to be able to monitor the progress, you will have to do the hash in small increments. You will then be able to calculate the percentage of the file that is done your self.

    The building blocks for this would be HashAlgorithm.TransformBlock and HashAlgorithm.TransformFinalBlock.

    Call TransformBlock in a loop, and use events, or BackgroundWorker.ReportProgress to communicate progress to the UI.

    This older question has an answer with a good example of using TransformBlock, and there is also an example in the docs for TransformBlock.