If my program is printing to the console, I perform word-wrapping in a certain way according to Console.WindowWidth by inserting newlines – and this works perfectly.
However if the output of the program is redirected to a file or another program I would like it to skip the word-wrapping. How can I detect when this is the case?
Console.WindowWidth returns the same number in both cases.
Bonus points if the solution can distinguish redirected Console.Out from redirected Console.Error.
p/invoke
GetFileType(GetStdHandle(STD_OUTPUT_HANDLE)), or call an innocuous console function likeGetConsoleScreenBufferInfoto check for invalid handle error. If you want to know about standard error, useSTD_ERROR_HANDLE. I believe you can even compare handles returned byGetStdHandle(STD_OUTPUT_HANDLE)andGetStdHandle(STD_ERROR_HANDLE)to detect stuff like2>&1.