Skip to content

Instantly share code, notes, and snippets.

@atifaziz
Created April 3, 2014 08:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atifaziz/9950740 to your computer and use it in GitHub Desktop.
Save atifaziz/9950740 to your computer and use it in GitHub Desktop.
Standard streams (stdin, stdout, and stderr) redirection detection
using System;
using System.Runtime.InteropServices;
// http://stackoverflow.com/a/3453272/6682
static class ConsoleRedirection
{
// http://msdn.microsoft.com/en-us/library/system.console.isinputredirected.aspx
public static bool IsInputRedirected() { return IsRedirected(StdHandle.Stdin); }
// http://msdn.microsoft.com/en-us/library/system.console.isoutputredirected.aspx
public static bool IsOutputRedirected() { return IsRedirected(StdHandle.Stdout); }
// http://msdn.microsoft.com/en-us/library/system.console.iserrorredirected.aspx
public static bool IsErrorRedirected() { return IsRedirected(StdHandle.Stderr); }
static bool IsRedirected(StdHandle handle) { return FileType.Char != GetFileType(GetStdHandle(handle)); }
// ReSharper disable UnusedMember.Local
enum FileType { Unknown, Disk, Char, Pipe }; // ReSharper restore UnusedMember.Local
enum StdHandle { Stdin = -10, Stdout = -11, Stderr = -12 };
[DllImport("kernel32.dll")] static extern FileType GetFileType(IntPtr hdl);
[DllImport("kernel32.dll")] static extern IntPtr GetStdHandle(StdHandle std);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment