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