更新时间:2023-11-29 16:05:16
我一直在使用Pieter的解决方案,直到我意识到它在Mono中不起作用。当用管道输入检索 Console.KeyAvailable
时,Mono不会引发异常。因此,这种方法没有帮助。
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.
但是,从.NET 4.5开始, Console
实际上提供了一个新的字段 IsInputRedirected
删除阴影和不必要的 try
/ catch
:
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);