控制台应用程序中的进度条问题

时间:2014-10-01 18:22:16

标签: c# progress-bar console-application

我在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 of 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。 但我想从5个中的1个中开始打印,5个中的2个... 5个中的5个。

所以我把我的for循环改为从位置1开始。

for (int i = 1; i< xmlFilePath.Length; i++)
{
}

在这种情况下,它只会处理4个文件,因此我将xmlFilePath.Length更改为xmlFilePath.Length +1,但我收到index out bound例外。

有关如何解决此问题的任何建议?

2 个答案:

答案 0 :(得分:4)

数组索引是基于0的,所以你必须从0开始。你可以做的是从索引0开始,但是当将数据传递到你的进度条时添加1.

for (int i = 0; i < xmlFilePath.Length; i++)
{
    ProgressBar(i + 1, xmlFilePath.Length);
}

答案 1 :(得分:1)

说谎你的进度条

for (int i = 0; i < xmlFilePath.Length; i++)
{
   ProgressBar(i + 1, xmlFilePath.Length);
}

另一个小问题。
我认为您需要更改停止绘制绿色块的条件

int position = 1;
for (int i = 0; i <= onechunk * progress; i++)
{
    Console.BackgroundColor = ConsoleColor.Green;

    Console.CursorLeft = position++;
    Console.Write(" ");
}

否则最后一个焦点位置仍为黑色。

相关问题