计算进度百分比

发布于 2024-12-05 09:33:26 字数 398 浏览 1 评论 0原文

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

例如:

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 = ???
}

`

我该怎么做?提前致谢

How I calculate the percentage of a file that is loading in loop?

For example:

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 = ???
}

`

How I do this? Thanks in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

惟欲睡 2024-12-12 09:33:26

您需要知道预期的最终输出量 - 否则您无法给出已完成输出的比例。

如果您知道它将达到某个大小,则可以使用:

// *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;
}

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

不过,在开始之前您仍然需要知道总长度,否则您不可能按比例给出进度。

You'd need to know the eventual amount of output to expect - otherwise you have no way of giving a proportion of the output which has already been completed.

If you know it's going to be a certain size, you can use:

// *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;
}

This assumes a progress bar with a minimum of zero and a maximum of 100 - it also assumes that the overall length is less than int.MaxValue / 100. Another approach is simply to make the progress bar maximum value the overall length, and set the progress bar value to builder.Length.

You'll still need to know the overall length before you start though, otherwise you can't possibly give progress as a proportion.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文