How do I create a console progress bar?

Category: System, viewed: 622 time(s).

The code snippet below shows you the trick on creating progress bar in a console application.

using System;
using System.Text;
using System.Threading;

namespace Kodecsharp.Example.System
{
    class ConsoleProgressBar
    {
        [STAThread]
        public static void Main(string[] args)
        {
            StringBuilder progress = new StringBuilder();
            for (int i = 1; i <= 100; i++)
            {
                //
                // Increments progress bar indicator.
                //
                if (i % 10 == 0)
                {
                    progress.Append("=");
                }

                //
                // Prints the progress bar and return to the beginning of
                // the line using carriage return (\r). Using carriege
                // return makes the next print process occurs in the same
                // line of the console.
                //
                Console.Write(i + "% " + progress.ToString() + "\r");

                //
                // Adds delay to simulate a process.
                //
                Thread.Sleep(100);
            }

            Console.Write("Done!          ");
            Console.Read();
        }
    }
}