Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReadKey not working in .net core

Tags:

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?

like image 464
Guerrilla Avatar asked Oct 24 '17 02:10

Guerrilla


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 data type is console ReadKey?

Console.ReadKey() It obtains the next character or function key pressed by the user. In simple words, it read that which key is pressed by user and return its name. it does not require to press enter key before entering. Note: It is STRUCT Data type which is ConsoleKeyInfo.


1 Answers

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

like image 192
Guerrilla Avatar answered Sep 28 '22 08:09

Guerrilla