Last active
April 3, 2023 08:45
-
-
Save danzuep/6de3b8fde8968e497a3b67c3fc85b918 to your computer and use it in GitHub Desktop.
Reads a password from the console, but only displays "*" characters.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static string ReadPasswordFromConsole() | |
{ | |
Console.TreatControlCAsInput = true; | |
var sb = new StringBuilder(); | |
while (Console.ReadKey(true) is ConsoleKeyInfo cki && cki.Key != ConsoleKey.Enter) | |
{ | |
if (cki.Modifiers == ConsoleModifiers.Control && cki.Key == ConsoleKey.C) | |
{ | |
break; | |
} | |
else if (sb.Length > 0 && cki.Key == ConsoleKey.Backspace) | |
{ | |
Console.Write("\b \b"); | |
sb.Length--; | |
continue; | |
} | |
else | |
{ | |
Console.Write('*'); | |
sb.Append(cki.KeyChar); | |
} | |
} | |
Console.WriteLine(); | |
return sb.ToString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment