我正在使用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);
}
}我的问题是,有没有可能获得缓冲区的“进度”?因为我猜它在内部运行着某种除法和循环。
发布于 2019-01-08 22:26:12
我尝试实现jdweng解决方案,但在访问线程以使用position变量更新我的进度条时遇到了问题。最后,我使用background_worker和自定义缓冲区重写了代码。这是它的一个示例。
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);
}
}https://stackoverflow.com/questions/54078795
复制相似问题