views:

363

answers:

2

I have a console app that performs a lengthy process.

I am printing out the percent complete on a new line, for every 1% complete.

How can I make the program print out the percent complete in the same location in the console window?

+11  A: 

Print \r to get back to the start of the line (but don't print a newline!)

For example:

using System;
using System.Threading;

class Test
{
    static void Main()
    {
        for (int i=0; i <= 100; i++)
        {
            Console.Write("\r{0}%", i);
            Thread.Sleep(50);
        }
    }
}
Jon Skeet
Yep, this is the easiest way to do it. Make sure (if you are using it for strings of variable length) that you remember to overwrite with spaces at the end of lines. e.g. replacing "99% complete" with "Done!" will show the line "Done!omplete" - not ideal. :)
ZombieSheep
You have an off by one error :P
Noon Silk
Jon Skeet: Sorry, it seems stack overflow won't let me rollback ronnies edit to your post correctly. Please attempt it yourself.
Noon Silk
It may be boringly worth noting that this code won't work when run on an operating system that isn't Windows. I'd recommend the `SecCursorPosition` approach.
Noon Silk
@silky: I've just run it on Linux with Mono, and it worked with no problems. However, using your suggestion didn't - because it put the percentage at the top of the screen, rather than on the same line as "Hello : ". That's fixable of course, but it does show the advantage of a simple solution :)
Jon Skeet
Okay, I'll still hazard a guess that on a Mac it'll go to a new line. Granted, though, the SecCursorPos doesn't work unless you also set the right row.
Noon Silk
@silky: On MacOS X I'd expect it to be fine - it's only MacOS 9 that treats \r as a newline, I believe. Are there any implementations of .NET for MacOS 9?
Jon Skeet
+3  A: 

You may use:

Console.SetCursorPosition();

To set the position appropriately.

Like so:

Console.Write("Hello : ");
for(int k = 0; k <= 100; k++){
    Console.SetCursorPosition(8, 0);
    Console.Write("{0}%", k);
    System.Threading.Thread.Sleep(50);
}

Console.Read();
Noon Silk