Created
June 19, 2015 12:39
-
-
Save tkouba/032f13bc5b513d42de57 to your computer and use it in GitHub Desktop.
Read password from console
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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