在Git Bash中运行.NET Core控制台应用时,ReadKey为何抛出异常?
解决Git Bash中使用
Console.ReadKey()抛出异常的问题 我之前也踩过这个坑,咱们先看具体场景:
这段C#代码:
ConsoleKeyInfo cki; while((cki = Console.ReadKey(true)).Key != ConsoleKey.Escape) { Console.WriteLine(cki.Key); }
用dotnet run在CMD或者PowerShell里运行完全正常,但切换到Git Bash执行时,直接抛出了异常:
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本质是基于msys的模拟终端,和Windows原生控制台的交互机制不一样。Console.ReadKey()依赖Windows原生控制台的底层交互能力来捕获按键,而Git Bash会重定向控制台输入,导致这个方法无法正常工作。
解决方案
有几种方式可以解决这个问题,按需选择:
方案1:改用Console.Read()替代
如果不需要捕获组合键(比如Shift+A这类),可以直接换成Console.Read(),它能在Git Bash里正常读取输入,修改后的代码如下:
int inputChar; // 27是Escape键的ASCII码 while((inputChar = Console.Read()) != 27) { Console.WriteLine((ConsoleKey)inputChar); }
方案2:环境兼容处理
如果必须保留Console.ReadKey()的功能(比如需要识别组合键),可以先判断当前运行环境是否为Git Bash,再做分支处理:
ConsoleKeyInfo cki; // 通过TERM环境变量判断是否在Git Bash/msys环境 bool isGitBash = Environment.GetEnvironmentVariable("TERM")?.Contains("msys") == true; if (isGitBash) { int inputChar; while((inputChar = Console.Read()) != 27) { Console.WriteLine((ConsoleKey)inputChar); } } else { // 原生控制台环境正常使用ReadKey() while((cki = Console.ReadKey(true)).Key != ConsoleKey.Escape) { Console.WriteLine(cki.Key); } }
方案3:用winpty运行程序(无需修改代码)
如果不想改动代码,可以在Git Bash里用winpty命令来启动程序,它会模拟Windows原生控制台环境,让Console.ReadKey()正常工作:
winpty dotnet run
内容的提问来源于stack exchange,提问作者user13602381
相关产品推荐
相关产品推荐

