Skip to content

Instantly share code, notes, and snippets.

@philippwiddra
Created June 23, 2016 08:14
Show Gist options
  • Save philippwiddra/313796d08c7af2e1b885cc77cc16249a to your computer and use it in GitHub Desktop.
Save philippwiddra/313796d08c7af2e1b885cc77cc16249a to your computer and use it in GitHub Desktop.
Simple function to let the user enter a password for C# console applications.
static string ConsoleReadPassword()
{
StringBuilder stringBuilder = new StringBuilder();
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
while (keyInfo.Key != ConsoleKey.Enter)
{
if (keyInfo.Key == ConsoleKey.Backspace)
{
stringBuilder.Remove(stringBuilder.Length - 1, 1);
Console.CursorLeft = Console.CursorLeft - 1;
Console.Write(" ");
Console.CursorLeft = Console.CursorLeft - 1;
}
else if (!char.IsControl(keyInfo.KeyChar))
{
Console.Write("*");
stringBuilder.Append(keyInfo.KeyChar);
}
keyInfo = Console.ReadKey(true);
}
Console.Write("\n");
return stringBuilder.ToString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment