How can I update the current line in a C# Windows Console App? provides several options on how a line of text written to the console can be refreshed. Unfortunately, none of the main options work correctly if the console app's output is redirected to a file.
MyApp.exe > outfile.txt
Is there a way to update a line written to the console that works with output redirection?
For example, using any of the below approaches, I can refresh the line Processing xx of yyyy
on the screen as records are processed. If the application aborts before processing is complete, the Processing
line will reflect the last line successfully processed (so long as the application doesn't die will updating that line). When Console.Out is redirected, I'd like the output file to similarly be updated in real time.
Approaches That Don't Work
Carriage Return Method
With the carriage return method, both old and new line are written to the output file:
Console.Write("Processed 1 of 10");
Console.Write("\rProcessed 2 of 10");
Results in:
Processed 1 of 10Processed 2 of 10
Cursor Position Manipulation
Manipulating cursor position crashes the app:
Console.Write("Processed 1 of 10");
Console.SetCursorPosition(Console.CursorLeft - 7, Console.CursorTop);
Console.Write("2 of 10");
Causes:
Unhandled Exception: System.ArgumentOutOfRangeException: The value must
be great er than or equal to zero and less than the console's buffer size
in that dimension.
Parameter name: left
Actual value was -7.
Backspacing
The backspace method outputs both lines to the file along with the backspace characters:
Console.WriteLine("Processed 1 of 10");
Console.Write("\b\b\b\b\b2 of 10");
Produces:
Processed 1 of 10
{5 backspace characters}2 of 10