计算进度百分比

Kak*_*shi 7 .net c# file progress-bar

我如何计算循环加载的文件的百分比?

例如:

ProcessStartInfo p = new ProcessStartInfo();
Process process = Process.Start(p);
StreamReader sr = process.StandardOutput;
char[] buf = new char[256];
string line = string.Empty;
int count;

while ((count = sr.Read(buf, 0, 256)) > 0)
{
    line += new String(buf, 0, count);
    progressBar.Value = ???
}
Run Code Online (Sandbox Code Playgroud)

`

我是怎么做到的 提前致谢

Jon*_*eet 12

您需要知道预期的最终输出量 - 否则您无法给出已经完成的输出的一部分.

如果你知道它将是一定的尺寸,你可以使用:

// *Don't* use string concatenation in a loop
StringBuilder builder = new StringBuilder();
int count;
while ((count = sr.Read(buf, 0, 256)) > 0)
{
    builder.Append(buf, 0, count);
    progressBar.Value = (100 * builder.Length) / totalSize;
}
Run Code Online (Sandbox Code Playgroud)

假设进度条的最小值为零且最大值为100 - 它还假设总长度小于int.MaxValue/ 100.另一种方法是简单地使进度条最大值为总长度,并设置进度条值到builder.Length.

在开始之前你仍然需要知道整体长度,否则你不可能按比例取得进步.