.Net Core application console how to hide password
I was working on a Command-line Interface (CLI) made with .Net Core.
And I ask myself how I can hide a password when the user is typing it? Like it’s the case with Linux’s Terminal.
But, in fact, It’s pretty easy
private string AskForPassword() { Console.Write("Please give us your password : "); string password = ""; ConsoleKeyInfo info = Console.ReadKey(true); while (info.Key != ConsoleKey.Enter) { if (info.Key != ConsoleKey.Backspace) { password += info.KeyChar; info = Console.ReadKey(true); } else if (info.Key == ConsoleKey.Backspace) { if (!string.IsNullOrEmpty(password)) { password = password.Substring (0, password.Length - 1); } info = Console.ReadKey(true); } } return password; }
Leave a Reply