Ben Gribaudo
Ben Gribaudo

Reputation: 5147

.Net Console App - Updating the Current Line in a way that works with Output Redirection

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

Upvotes: 1

Views: 803

Answers (1)

Christian.K
Christian.K

Reputation: 49300

That cannot possible work the way you expect it to. Even the concept of "current line" is at best blurred when output is redirected.

  • The console methods / properties that alter the cursor position on the screen are meaningless when the output is redirected.

  • The redirected output is sequential, so once something has been written to the output file, it is there.

You should consider a different strategy, i.e. changing how and what you write if you detect that the output is redirected. Use Console.IsOutputRedirected and/or Console.IsErrorRedirected, respectively.

For example:

 if (Console.IsOutputRedirected) {
    // Simply output every "line" as it comes.
    Console.WriteLine(text);
 } else {
    // Overwrite the "current line" with the next, if any.
    Console.Write(text);
    Console.SetCursporPosition(0, Cursor.CursorTop);
 }

Upvotes: 2

Related Questions