Last active
December 21, 2015 00:38
-
-
Save jvandertil/6221439 to your computer and use it in GitHub Desktop.
Function to read input from the Console while masking the output. Useful for reading passwords.
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> | |
/// Reads the next line of characters from the standard input stream (Console). | |
/// Outputs a '*' character for each character read, instead of the actual character. | |
/// </summary> | |
/// <returns>The next line of characters from the input stream.</returns> | |
public static string ReadLineMasked() | |
{ | |
var password = new StringBuilder(); | |
ConsoleKeyInfo pressed; | |
do | |
{ | |
pressed = Console.ReadKey(true); | |
if (pressed.Key == ConsoleKey.Backspace) | |
{ | |
if (password.Length <= 0) | |
continue; | |
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop); // Go back 1 position | |
Console.Write(' '); // Erase * char | |
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop); // Go back once again, the erasing caused the cursor to move. | |
password.Remove(password.Length - 1, 1); // Remove char from string builder. | |
} | |
else | |
{ | |
Console.Write('*'); | |
password.Append(pressed.KeyChar); | |
} | |
} while (pressed.Key != ConsoleKey.Enter); | |
return password.ToString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can easily be modified to use a SecureString object. Info: http://msdn.microsoft.com/en-us/library/system.security.securestring.aspx