Skip to content

Instantly share code, notes, and snippets.

@OrigamiTech
Created May 2, 2011 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OrigamiTech/951680 to your computer and use it in GitHub Desktop.
Save OrigamiTech/951680 to your computer and use it in GitHub Desktop.
Read a password via command-line without showing the password
public static string ReadPassword()
{ return ReadPassword('*'); }
public static string ReadPassword(char passwordchar)
{
string pass = "";
char c = Console.ReadKey(true).KeyChar;
while(c != (char)0x0D)
{
if(c == 0x08)
{
if(pass.Length > 0)
{
pass = pass.Substring(0, pass.Length - 1);
if(Console.CursorLeft == 0)
{
Console.CursorLeft = Console.WindowWidth - 1;
Console.CursorTop--;
Console.Write(' ');
Console.CursorLeft = Console.WindowWidth - 1;
Console.CursorTop--;
}
else
{
Console.CursorLeft--;
Console.Write(' ');
Console.CursorLeft--;
}
}
}
else
{
pass += c;
Console.Write(passwordchar);
}
c = Console.ReadKey(true).KeyChar;
}
Console.WriteLine();
return pass;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment