Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
566 views
in Technique[技术] by (71.8m points)

c# - ReadKey not working in .net core

I am trying to use ReadKey() to get a password field so it doesn't show in console for a .net core app I am running on Ubuntu.

This is code:

        while (true)

        {

            var key = System.Console.ReadKey(true);

            if (key.Key == ConsoleKey.Enter)

                break;

            Io.RootPass += key.KeyChar;

        } 

But I get this exception:

Exception has occurred: CLR/System.InvalidOperationException An unhandled exception of type 'System.InvalidOperationException' occurred in System.Console.dll: 'Cannot read keys when either application does not have a console or when console input has been redirected. Try Console.Read.'

ReadLine() works fine. Why doesn't ReadKey() work?

Edit:

Actually Console.ReadLine() doesn't work either it just doesn't throw an exception. The return value is not assigned when enter hit so program sticks.

I am guessing this is because linux terminal works differently. Is there a different interface for linux terminal that works?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Found my answer in OmniSharp Visual Code docs: https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md#console-terminal-window

Console (terminal) window

By default, processes are launched with their console output (stdout/stderr) going to the VS Code Debugger Console. This is useful for executables that take their input from the network, files, etc. But this does NOT work for applications that want to read from the console (ex: Console.ReadLine). For these applications, use a setting such as the following:

"console": "integratedTerminal" When this is set to integratedTerminal the target process will run inside VS Code's integrated terminal. Click the 'Terminal' tab in the tab group beneath the editor to interact with your application.

When this is set to externalTerminal the target process will run in a separate terminal.

I changed this setting in launch.json and now it works


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...