Over write text in a window's console application

Today I had a need to display a counter on a Console application and I was trying to think of a way to over write the existing number with the new number in the console window, using C#.  So after thinking about it for a minute it came to me, just write backspace characters.  Well anyways just incase anyone would ever need this here is a simple example: 

for(int i = 0; i < 1000; i++)
{
  if(i > 0)
    Console.WriteLine(new string('\b', (i-1).ToString().Length));

  Console.WriteLine(i.ToString());
}
Published Thursday, March 27, 2003 10:40 PM by puzzlehacker

Comments

# re: Over write text in a window's console application

I needed this today so thanks.  :-)

Thursday, February 08, 2007 5:30 AM by Gary Woodfine

# re: Over write text in a window's console application

I've just used this, but I had to replace WriteLine with Write

Thursday, March 08, 2007 8:01 PM by Stephen Paulger

# re: Over write text in a window's console application

Thanks Wes, I needed this for something.

Tuesday, May 01, 2007 11:21 AM by Ryan Reeves

# re: Over write text in a window's console application

Excellant worked a treat

Wednesday, July 09, 2008 6:21 AM by Michael

# re: Over write text in a window's console application

For what it's worth, here's another way:

using System;

using System.Threading;

namespace ConsoleApplication1

{

   class Program

   {

       static void Main(string[] args)

       {

           Console.CursorVisible = false;

           for (int i = 0; i < 30; i++)

           {

               int cursorLeft = Console.CursorLeft;

               int cursorTop = Console.CursorTop;

               Console.Write(string.Format("{0}/30", i + 1));

               if (i != 30)

               Console.SetCursorPosition(cursorLeft, cursorTop);

               Thread.Sleep(100);

           }

           Console.CursorVisible = true;

           Console.WriteLine();

           Console.WriteLine("Press the any key to exit...");

           Console.ReadKey();

       }

   }

}

Tuesday, July 07, 2009 2:56 PM by Robert

Leave a Comment

(required) 
(required) 
(optional)
(required)