本文介绍了如何检测 Console.In (stdin) 是否已被重定向?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个具有不同行为的控制台应用程序,具体取决于输入是来自键盘还是来自文件.

I want to write a console application that have a different behavior depending if the input is coming from keyboard or from, say, a file.

有可能吗?在 C# 中最优雅的方法是什么?

Is it possible? What's the most elegant way to do it in C#?

推荐答案

您可以通过 p/invoking Windows FileType() 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 中的 Console 类.如果没有署名,我可能会添加:( 只需使用相应的方法而不是这个助手类.


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-us/library/system.console.isoutputredirected.aspxhttps://msdn.microsoft.com/en-us/library/system.console.isinputredirected.aspxhttps://msdn.microsoft.com/en-us/library/system.console.iserrorredirected.aspx

这篇关于如何检测 Console.In (stdin) 是否已被重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 19:30