Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why ReadKey throws exception while running a .net-core console app from Git Bash?

This is the code:

ConsoleKeyInfo cki;

while((cki = Console.ReadKey(true)).Key != ConsoleKey.Escape)
{
    Console.WriteLine(cki.Key);
}

When i run it from cmd or powershell with dotnet run everything works fine. However when i run it from Git Bash it throws the following exception:

Unhandled exception. System.InvalidOperationException: Cannot read keys when either application does not have a console or when console input has been redirected. Try Console.Read.

like image 913
user13602381 Avatar asked Jun 19 '20 11:06

user13602381


People also ask

What is ReadKey () in C#?

ReadKey() Obtains the next character or function key pressed by the user. The pressed key is displayed in the console window. public: static ConsoleKeyInfo ReadKey(); C# Copy.

What does console ReadKey true do?

ReadKey() Method makes the program wait for a key press and it prevents the screen until a key is pressed. In short, it obtains the next character or any key pressed by the user.


1 Answers

Presumably, then, Git Bash is using IO redirection - which it is allowed to do - and the others ... aren't. The solution, then, is to use Read rather than ReadKey - at least if redirection is in play. You can probably detect this via Console.IsInputRedirected - and choose the most useful strategy for what is possible, but: you won't be able to detect keys in the same way, so you may need to have a slightly different user-experience in this scenario.

like image 168
Marc Gravell Avatar answered Nov 15 '22 01:11

Marc Gravell