如何检测是否Console.In(标准输入)已经重定向? [英] How to detect if Console.In (stdin) has been redirected?

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

问题描述

我想写具有不同的行为取决于如果输入是从键盘或从,比方说,一个文件来一个控制台应用程序。

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 /找出调用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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆