Issues with Console APIs when stdout is redirected to a file [Ravi Krishnaswamy]

When you redirect stdout of your consoleapp to a file, you can expect that a number of Console APIs won't work quite right. For ex, MoveBufferArea is an obvious candidate of something that can't be supported. In this situation you will get an IOException saying that the handle is invalid or something like that. We are throwing here not specifically because the output is redirected but mostly because we can't get a console handle.

Recently, we changed the behavior of some of the Console APIs such as BackgroundColor/ForegroundColor/ResetColor to be essentially nop if we can't get hold of a console handle. Seems like a reasonable thing to do.

Unfortunately, we didn't do a full review of all the Console APIs and see whether we should extend the nop behavior to other benign cadidates such as Console.SetConsoleCursorPosition, Console.Clear etc. So, some of Console APIs are still broken for redirection scenarios in Whidbey.

What this means is, to enable stdout redirection of you app, you essentially need to anticipate and catch the IOException around all Console APIs. This option is less than enterprising but would work. Alternatively, you could P/Invoke and call GetStdHandle(Win32Native.STD_OUTPUT_HANDLE) and see it is not returning INVALID_HANDLE_VALUE. Again, this is something that should be handled internally by the Console APIs where appropriate.

Ravi Krishnaswamy



Comments (5)

  1. Anonymous says:

    Does this mean that it won’t get fixed in time for .NET 2.0? Or that it is only broken for the current beta?

  2. Anonymous says:

    This is so unhelpful. Context of version is important. Plus, how could something so fundamental have been missed?

  3. Anonymous says:

    Hopefully you guys plan to fix this before 2.0 ships? It’s always so much better to get the API correct from the start or we will wind up with System.Console2.

  4. Anonymous says:

    At least provide IsRedirected property

  5. Anonymous says:

    We already have an action item to review all Console APIs regarding this behavior. Thanks for the feedback

Skip to main content