Checking Standard Input in C#

后端 未结 3 1310
花落未央
花落未央 2021-02-04 07:33

I\'m writing a small command line utility whose purpose is to parse the output of another utility. I want it to be invokable in two ways:

c:\\> myutility file         


        
相关标签:
3条回答
  • 2021-02-04 07:49

    I've been using Pieter's solution for a while until I realised it doesn't work in Mono. Mono doesn't throw an exception when retrieving Console.KeyAvailable with piped input, so that approach doesn't help.

    However, as of .NET 4.5, Console actually provides a new field IsInputRedirected which makes this a lot simpler, removes the obscurity and the unnecessary try/catch:

    TextReader reader;
    
    if (args.Length > 1) {
        reader = new StreamReader(new FileStream(args[1], FileMode.Open));
    } else {
        if (Console.IsInputRedirected) {
            reader = Console.In;
        } else {
            Console.WriteLine("Error, need data");
            return;
        }
    }
    
    Process(reader);
    
    0 讨论(0)
  • Looks like you should be able to use some Windows API calls to determine that. Hans Passant's answer even has a helper class to wrap it all up.

    0 讨论(0)
  • 2021-02-04 08:03

    The quick and dirty way is to wrap Console.KeyAvailable in a try/catch and if that throws, you know that input is redirected from a file. It's not very unusual to use try/catch to detect a state when you cannot find an appropriate method to do the checking for you.

    0 讨论(0)
提交回复
热议问题