【发布时间】:2014-10-01 18:22:15
【问题描述】:
我正在 C# 控制台应用程序中显示进度条。它正在处理一个小错误。
这是进度条代码:
private static void ProgressBar(int progress, int total)
{
//draw empty progress bar
Console.CursorLeft = 0;
Console.Write("["); //start
Console.CursorLeft = 32;
Console.Write("]"); //end
Console.CursorLeft = 1;
float onechunk = 30.0f / total;
//draw filled part
int position = 1;
for (int i = 0; i < onechunk * progress; i++)
{
Console.BackgroundColor = ConsoleColor.Green;
Console.CursorLeft = position++;
Console.Write(" ");
}
//draw unfilled part
for (int i = position; i <= 31; i++)
{
Console.BackgroundColor = ConsoleColor.Black;
Console.CursorLeft = position++;
Console.Write(" ");
}
//draw totals
Console.CursorLeft = 35;
Console.BackgroundColor = ConsoleColor.Black;
Console.Write(progress.ToString() + " of " + total.ToString() + " ");
}
如果它总共处理了 5 个文件,它将显示:
4 个,共 5 个
即使它正确处理了所有 5 个文件。
例如,我将 XML 文件从目录加载到字符串数组中。
string[] xmlFilePath = Directory.GetFiles(xmlFullpath, "*.xml");
然后我有一个for loop,在其中我调用我的进度条函数。
for (int i = 0; i < xmlFilePath.Length; i++)
{
ProgressBar(i, xmlFilePath.Length);
}
这就是我的工作方式。我知道,因为它从位置 0 开始,它将打印 0 1 2 3 4 out of 5。 但我想从 1 of 5、2 of 5 ... 5 of 5 开始打印。
所以我将 for 循环更改为从位置 1 开始。
for (int i = 1; i< xmlFilePath.Length; i++)
{
}
在这种情况下,它只会处理 4 个文件,所以我将 xmlFilePath.Length 更改为 xmlFilePath.Length +1 但我收到了 index out bound 异常。
关于如何解决此问题的任何建议?
【问题讨论】:
标签: c# progress-bar console-application