Skip to content

Instantly share code, notes, and snippets.

@danzuep
Last active April 3, 2023 08:45
Show Gist options
  • Save danzuep/6de3b8fde8968e497a3b67c3fc85b918 to your computer and use it in GitHub Desktop.
Save danzuep/6de3b8fde8968e497a3b67c3fc85b918 to your computer and use it in GitHub Desktop.
Reads a password from the console, but only displays "*" 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