0

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);
}
YS Wang
  • 177
  • 13

1 Answers1

2

The function you quote, originally by Hans Passant, was added to the console in .NET 4.5 (see Console.IsOutputRedirected et al)

Interestingly enough, the implementation in .NET is capable of detecting a redirect to NUL. It does this by doing an additional check whenever the FileType check yields false:

int mode;
bool success = Win32Native.GetConsoleMode(ioHandle, out mode);
return !success;

If you are on .NET 4.5, simply use the built-in function. If not, duplicating this extra check should solve your problem.

Community
  • 1
  • 1
Paul-Jan
  • 16,746
  • 1
  • 63
  • 95