Roman Starkov
Roman Starkov

Reputation: 61412

How can I determine whether Console.Out has been redirected to a file?

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.

Upvotes: 17

Views: 3930

Answers (6)

Roger Lipscombe
Roger Lipscombe

Reputation: 91845

.NET 4.5 adds Console.IsOutputRedirected and Console.IsErrorRedirected.

Upvotes: 15

Anton Tykhyy
Anton Tykhyy

Reputation: 20076

p/invoke GetFileType(GetStdHandle(STD_OUTPUT_HANDLE)), or call an innocuous console function like GetConsoleScreenBufferInfo to check for invalid handle error. If you want to know about standard error, use STD_ERROR_HANDLE. I believe you can even compare handles returned by GetStdHandle(STD_OUTPUT_HANDLE) and GetStdHandle(STD_ERROR_HANDLE) to detect stuff like 2>&1.

Upvotes: 11

ibz
ibz

Reputation: 46729

Don't do that! Just pass an additional command line parameter that specifies the formatting you want to be applied. It's simpler, cleaner, and easier to understand both by people that will use your app and by people who will work on your code.

Upvotes: 0

Joe Albahari
Joe Albahari

Reputation: 30934

You need to use reflection - a bit grubby but the following will work:

static bool IsConsoleRedirected()
{
    var writer = Console.Out;
    if (writer == null || writer.GetType ().FullName != "System.IO.TextWriter+SyncTextWriter") return true;
    var fld = writer.GetType ().GetField ("_out", BindingFlags.Instance | BindingFlags.NonPublic);
    if (fld == null) return true;
    var streamWriter = fld.GetValue (writer) as StreamWriter;
    if (streamWriter == null) return true;
    return streamWriter.BaseStream.GetType ().FullName != "System.IO.__ConsoleStream";
}

Upvotes: 2

Adam Robinson
Adam Robinson

Reputation: 185643

While this is a little shady and probably isn't guaranteed to work, you can try this:

bool isRedirected;

try
{
    isRedirected = Console.CursorVisible && false;
}
catch
{
    isRedirected = true;
}

Calling CursorVisible throws an exception when the console is redirected.

Upvotes: 8

Andrew Hare
Andrew Hare

Reputation: 351516

Why does the ouput wrap in the redirected file? The wrapping that the console does is not by means of line breaks. In other words this string:

hello my name is Andrew Hare

would wrap in a skinny console like this:

hello my nam
e is Andrew
Hare

but if you were to redirect the output to a file it would be written like this:

hello my name is Andrew Hare

since there are no true line-breaks in the output.

Upvotes: 0

Related Questions