C# BufferedStream - Is it possible to know advancement?

480 Views Asked by At

I'm writing a simple checksum generator app using C# for large files. It's working quite fine, but users would like to see some sort of progress bar since the app freezes for a a few dozen seconds.

Here is a a sample of code I use (BufferedStream increased a lot the app performance):

private static string GetSHA5(string file)
{
    using (var stream = new BufferedStream(File.OpenRead(file), 1200000))
    {
        var sha5 = new SHA512Managed();
        byte[] checksum_sha5 = sha5.ComputeHash(stream);
        return BitConverter.ToString(checksum_sha5).Replace("-", String.Empty);
    }
}

My question is, is it possible to get the buffer "progress" ? Because I guess internally it operates some sort of division and looping.

1

There are 1 best solutions below

0
On

I tried implementing jdweng solution but I had trouble accessing threads to update my progress bar with the position variable. In the end I rewrote my code using background_worker and a custom buffer. Here is a sample of a it.

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    dynamic data = e.Argument;
    string fPath = data["file"];
    byte[] buffer;
    int bytesRead;
    long size;
    long totalBytesRead = 0;
    using (Stream file = File.OpenRead(fPath))
    {
        size = file.Length;
        progressBar1.Visible = true;
        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 void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}
  private void md5HashBtn_Click(object sender, EventArgs e)
        {
            if (MD5TextBox.Text.Length > 0)
            {
                Dictionary<string, string> param = new Dictionary<string, string>();
                param.Add("algo", "MD5");
                param.Add("file", MD5TextBox.Text);
                backgroundWorker1.RunWorkerAsync(param);
            }
        }