C#BufferedStream-是否可以知道进度?

时间:2019-01-07 17:09:55

标签: c# bufferedstream

我正在使用C#编写用于大文件的简单校验和生成器应用程序。它工作正常,但由于该应用程序冻结了几十秒钟,因此用户希望看到某种进度条。

这里是我使用的代码示例(BufferedStream提高了应用程序的性能):

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

我的问题是,能否获得缓冲区“ progress”?因为我在内部猜测它会进行某种除法和循环。

1 个答案:

答案 0 :(得分:1)

我尝试实现jdweng解决方案,但是在访问线程以使用position变量更新进度栏时遇到麻烦。最后,我使用background_worker和自定义缓冲区重写了我的代码。这是一个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);
            }
        }