且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检测是否Console.In(标准输入)已经重定向?

更新时间:2023-11-18 09:23:28

您可以通过P /找出调用Windows的文件类型()API函数。这里有一个辅助类:

You can find out by p/invoking the Windows FileType() API function. Here's a helper class:

using System;
using System.Runtime.InteropServices;

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)); }
    }

    // P/Invoke:
    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);
}

用法:

bool inputRedirected = ConsoleEx.IsInputRedirected;


更新:已添加到控制台类.NET 4.5这些方法。没有归属我要补充:(只需使用相应的方法,而不是这个辅助类。


UPDATE: these methods were added to the Console class in .NET 4.5. Without attribution I might add :( Simply use the corresponding method instead of this helper class.

https://msdn.microsoft.com/en-美国/库/ system.console.isoutputredirected.aspx
https://msdn.microsoft.com/en-us/library /system.console.isinputredirected.aspx
https://msdn.microsoft.com/en-us/library/system.console.iserrorredirected.aspx