Skip to content

Instantly share code, notes, and snippets.

@tkouba
Created June 19, 2015 12:39
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 tkouba/032f13bc5b513d42de57 to your computer and use it in GitHub Desktop.
Save tkouba/032f13bc5b513d42de57 to your computer and use it in GitHub Desktop.
Read password from console
/// <summary>
/// Read password from console
/// </summary>
/// <param name="prompt">Password prompt</param>
/// <param name="mask">Password mask char, usually '*'</param>
/// <returns>Password</returns>
public static string ReadPassword(string prompt, char mask)
{
Stack<String> pwdStack = new Stack<String>();
if (!String.IsNullOrEmpty(prompt))
{
Console.Write(prompt);
if (!prompt.EndsWith(" "))
Console.Write(' ');
}
for (ConsoleKeyInfo cki = Console.ReadKey(true); cki.Key != ConsoleKey.Enter; cki = Console.ReadKey(true))
{
if (cki.Key == ConsoleKey.Backspace)
{
if (pwdStack.Count > 0)
{
pwdStack.Pop();
if (mask != '\0' &&
mask > ' ')
{
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
Console.Write(' ');
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
}
}
}
else
{
if (cki.KeyChar != '\0' &&
cki.KeyChar > ' ')
{
pwdStack.Push(cki.KeyChar.ToString());
if (mask != '\0' &&
mask > ' ')
Console.Write(mask);
}
}
}
Console.WriteLine();
return String.Join(String.Empty, pwdStack.ToArray().Reverse());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment