【问题标题】:Issue with Progress bar in console application控制台应用程序中的进度条问题
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      对你的进度条说谎

      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(" ");
      }
      

      否则最后一个字符位置保持黑色。

      【讨论】:

        猜你喜欢
        • 2014-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多