Command Line Progress Bar C#

I have written quite a few command line applications and was looking for a way to show progress in much the same way as a gui progress bar. The below code accomplishes this. Simply add this to your application and call it from within your processing loop:

 

int Total = results.Count;
int i = 1;
foreach (SearchResult result in results)
{
drawTextProgressBar(i, Total);
i++;
}

private static void drawTextProgressBar(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.Gray;
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() + " "); //blanks at the end remove any excess
}
Related Posts with Thumbnails

Tags: