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

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

问题描述

这是代码:

ConsoleKeyInfo cki;

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

当我使用 dotnet 从 cmd 或 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.

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

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