Skip to content

Instantly share code, notes, and snippets.

@SplittyDev
Created May 10, 2015 23:32
Show Gist options
  • Save SplittyDev/13b0bc01971f6f4eff81 to your computer and use it in GitHub Desktop.
Save SplittyDev/13b0bc01971f6f4eff81 to your computer and use it in GitHub Desktop.
Read password from stdin
public static string ReadPassword () {
const char PLACEHOLDER = '*';
var accum = new StringBuilder ();
while (true) {
var key = Console.ReadKey (true);
if (key.Key == ConsoleKey.Backspace) {
if (accum.Length > 0) {
accum.Remove (accum.Length - 1, 1);
Console.Write ("\b \b");
}
} else if (key.Key == ConsoleKey.Enter) {
Console.Write ('\n');
return accum.ToString ();
} else {
Console.Write (PLACEHOLDER);
accum.Append (key.KeyChar);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment