Created
April 3, 2014 08:44
-
-
Save atifaziz/9950740 to your computer and use it in GitHub Desktop.
Standard streams (stdin, stdout, and stderr) redirection detection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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