Linux上的.NET Core:stdout是否重定向?

xmjla07d  于 2023-04-11  发布在  Linux
关注(0)|答案(1)|浏览(105)

在Windows上,我使用以下代码来确定是否为当前运行的进程重定向stdout流:

private static bool? isOutputRedirected;

public static bool IsOutputRedirected
{
    get
    {
        if (isOutputRedirected == null)
        {
            isOutputRedirected =
                GetFileType(GetStdHandle(StdHandle.Output)) != FileType.FileTypeChar ||
                !GetConsoleMode(GetStdHandle(StdHandle.Output), out _);
            // Additional GetConsoleMode check required to detect redirection to "nul"
        }
        return isOutputRedirected == true;
    }
}

private enum StdHandle : int
{
    Input = -10,
    Output = -11,
    Error = -12,
}

private enum FileType : uint
{
    FileTypeChar = 0x0002,
    FileTypeDisk = 0x0001,
    FileTypePipe = 0x0003,
    FileTypeRemote = 0x8000,
    FileTypeUnknown = 0x0000,
}

[DllImport("kernel32.dll")]
private static extern FileType GetFileType(IntPtr hFile);

[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr GetStdHandle(StdHandle nStdHandle);

[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint lpMode);

我对其他两个标准流也有类似的属性。
当显示进度信息或尝试用新内容更新当前行时,需要使用此选项。当输出被重定向时,此选项没有用,因此应将输出减少为更简单的内容。
但是当在Linux(dotnet publish -r linux-arm)上运行时,这会像预期的那样失败。
我如何才能在Linux上确定同样的情况呢?web似乎对此一无所知(尚未)。

50pmv0ei

50pmv0ei1#

对于.NET Core,您可能需要查看Console.IsOutputRedirectedConsole.IsErrorRedirected
来源:https://learn.microsoft.com/en-us/dotnet/api/system.console?view=netcore-3.1

相关问题