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?
I was doing a search for this to see if the solution I wrote could be optimised for speed. What I wanted was a countdown timer, not just updating the current line. Here's what I came up with. Might be useful to someone
You can use the \b (backspace) escape sequence to backup a particular number of characters on the current line. This just moves the current location, it does not remove the characters.
For example:
Here, line is the percentage line to write to the console. The trick is to generate the correct number of \b characters for the previous output.
The advantage of this over the \r approach is that if works even if your percentage output is not at the beginning of the line.
From the Console docs in MSDN:
So - I did this:
Then I am able to control the output myself;
Another way of getting there.
Here is my take on s soosh's and 0xA3's answers. It can update the console with user messages while updating the spinner and has an elapsed time indicator aswell.
usage is something like this. class Program {
The
SetCursorPosition
method works in multi-threading scenario, where the other two methods don't