I wrote a console program I'd like to detect user is using redirection or not
I found the ConsoleEx class can meet my requirement except user redirect output stream to NUL device
Is there a way to distinguish user is redirecting the output to NUL?
For example, my application naming test.exe
ConsoleEx.IsOutputRedirected return true
test.exe > 001.txt
ConsoleEx.IsOutputRedirected return false
test.exe > NUL
test.exe
public static class ConsoleEx
{
public static bool IsOutputRedirected
{
get { return FileType.Char != GetFileType(GetStdHandle(StdHandle.Stdout)); }
}
public static bool IsInputRedirected
{
get { return FileType.Char != GetFileType(GetStdHandle(StdHandle.Stdin)); }
}
public static bool IsErrorRedirected
{
get { return FileType.Char != GetFileType(GetStdHandle(StdHandle.Stderr)); }
}
private enum FileType { Unknown, Disk, Char, Pipe };
private enum StdHandle { Stdin = -10, Stdout = -11, Stderr = -12 };
[DllImport("kernel32.dll")]
private static extern FileType GetFileType(IntPtr hdl);
[DllImport("kernel32.dll")]
private static extern IntPtr GetStdHandle(StdHandle std);
}