Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I update the current line in a C# Windows Console App?

When building a Windows Console App in C#, is it possible to write to the console without having to extend a current line or go to a new line? For example, if I want to show a percentage representing how close a process is to completion, I'd just like to update the value on the same line as the cursor, and not have to put each percentage on a new line.

Can this be done with a "standard" C# console app?

like image 829
IVR Avenger Avatar asked May 20 '09 15:05

IVR Avenger


People also ask

How to insert new line in Console WriteLine?

By using: \n – It prints new line. By using: \x0A or \xA (ASCII literal of \n) – It prints new line. By using: Console. WriteLine() – It prints new line.

How does WriteLine() method works?

WriteLine(String, Object, Object) Writes the text representation of the specified objects, followed by the current line terminator, to the standard output stream using the specified format information.


1 Answers

If you print only "\r" to the console the cursor goes back to the beginning of the current line and then you can rewrite it. This should do the trick:

for(int i = 0; i < 100; ++i) {     Console.Write("\r{0}%   ", i); } 

Notice the few spaces after the number to make sure that whatever was there before is erased.
Also notice the use of Write() instead of WriteLine() since you don't want to add an "\n" at the end of the line.

like image 88
shoosh Avatar answered Sep 21 '22 08:09

shoosh