So I decided to start programming in C#, and one of the things I did was to create a "pausec.exe" (a pause.exe clone). It works, but when calling it like:
< nul pausec
...it crashes. The error I get - translated from Spanish to the best of my knowledge - goes like this:
Unhandled exception: System.InvalidOperationException: Can't read keys when any of the applications doesn't have a console or when the console input has been redirected from a file. Try with Console.Read.
And the stacktrace telling me where the error is:
in System.Console.ReadKey(Boolean intercept)
in System.Console.ReadKey()
in pausec.Program.Main(String[] args)
This is the code I'm running:
using System;
namespace pausec
{
class Program
{
static void Main(string[] args)
{
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
Console.Write("\n");
}
}
}
I'm wondering if there's a workaround for this, maybe even a way to ignore the ReadKey
when using < nul
?
Any help is appreciated.
Thanks in advance
UPDATE: Found a way, by removing the intercept (as Alberto Solano suggested) and then, adding Console.Write("\b \b");
after the ReadKey
method, it works. Weird thing is, when I copy the application to my desktop, it doesn't wait for user input and closes automatically.
UPDATE 2: It works perfectly now. Thank you all for answering!
The console has a method that you can check to see if stdin has been redirected.
public static bool IsInputRedirected { get; }