Skip to content

Instantly share code, notes, and snippets.

@jstrassburg
Created February 26, 2014 19:08
Show Gist options
  • Save jstrassburg/9236252 to your computer and use it in GitHub Desktop.
Save jstrassburg/9236252 to your computer and use it in GitHub Desktop.
Read a password from the console in C#
public string GetPassword()
{
Console.Write("Enter password: ");
var password = new StringBuilder();
while (true)
{
var readKey = Console.ReadKey(true);
if (readKey.Key == ConsoleKey.Enter)
{
Console.Write("\n");
break;
}
if (readKey.Key == ConsoleKey.Backspace)
{
if (password.Length > 0)
{
password.Remove(password.Length - 1, 1);
Console.Write("\b \b");
}
}
else
{
password.Append(readKey.KeyChar);
Console.Write("*");
}
}
return password.ToString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment