为什么从Git Bash运行.net核心控制台应用程序时,ReadKey会引发异常? [英] Why ReadKey throws exception while running a .net-core console app from Git Bash?

查看:121
本文介绍了为什么从Git Bash运行.net核心控制台应用程序时,ReadKey会引发异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码:

ConsoleKeyInfo cki;

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

当我使用cmd或dotnet从powershell运行它时,一切正常.但是,当我从Git Bash运行它时,它将引发以下异常:

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:

未处理的异常.System.InvalidOperationException:当任一应用程序没有控制台或控制台输入已重定向时,无法读取键.尝试Console.Read.

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.

推荐答案

然后,Git Bash大概正在使用IO重定向-允许这样做-而其他...则不是.因此,解决方案是使用 Read 而不是 ReadKey -至少在进行重定向的情况下.您可能可以通过 Console.IsInputRedirected 检测,并为可能的情况选择最有用的策略,但是:您将无法检测,因此在这种情况下,您可能需要稍有不同的用户体验.

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.

这篇关于为什么从Git Bash运行.net核心控制台应用程序时,ReadKey会引发异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆