Improved version from @Fredrik Fjällström post:
https://stackoverflow.com/a/59668053/2935383
His version is great because you can also see the cursor and set password-*** char if necessary.
But what is still missing is the suppression of non-printable characters.
public static string GetPassword()
{
StringBuilder input = new StringBuilder();
while (true)
{
int x = Console.CursorLeft;
int y = Console.CursorTop;
ConsoleKeyInfo key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter)
{
Console.WriteLine();
break;
}
if (key.Key == ConsoleKey.Backspace && input.Length > 0)
{
input.Remove(input.Length - 1, 1);
Console.SetCursorPosition(x - 1, y);
Console.Write(" ");
Console.SetCursorPosition(x - 1, y);
}
else if( key.KeyChar < 32 || key.KeyChar > 126 )
{
Trace.WriteLine("Output suppressed: no key char"); //catch non-printable chars, e.g F1, CursorUp and so ...
}
else if (key.Key != ConsoleKey.Backspace)
{
input.Append(key.KeyChar);
Console.Write("*");
}
}
return input.ToString();
}