smr5
smr5

Reputation: 2793

Issue with Progress bar in console application

I'm displaying a progress bar in C# console application. It's doing what it should with one minor bug.

Here's the progress bar code:

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

If it processed total of 5 files it will display:

4 of 5

even though it correctly processed all 5 files.

For example, I load XML files from directory into a string array.

string[] xmlFilePath = Directory.GetFiles(xmlFullpath, "*.xml");

Then I have a for loop and inside of it I call my progress bar function.

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

This is how I have it working. I know since it starts at position 0 it will print 0 1 2 3 4 out of 5. But I want to start printing from 1 of 5, 2 of 5 ... 5 of 5.

So I changed my for loop to start at position 1.

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

At this case it will only process 4 files so I changed xmlFilePath.Length to xmlFilePath.Length +1 but I'm getting index out bound exception.

Any suggestions on how I can fix this?

Upvotes: 2

Views: 2978

Answers (2)

Steve
Steve

Reputation: 216293

Just tell a lie to your progressbar

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

Just another little problem.
I think you need to change condition that stops the drawing of the green blocks to

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

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

Otherwise the last char position remains black.

Upvotes: 1

Dave Zych
Dave Zych

Reputation: 21887

Array indexes are 0 based, so you have to start at 0. What you can do is start at index 0, but when passing the data to your progress bar add 1.

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

Upvotes: 4

Related Questions