Skip to content

Instantly share code, notes, and snippets.

@jvandertil
Last active December 21, 2015 00:38
Show Gist options
  • Save jvandertil/6221439 to your computer and use it in GitHub Desktop.
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.
/// <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();
}
@jvandertil
Copy link
Author

Can easily be modified to use a SecureString object. Info: http://msdn.microsoft.com/en-us/library/system.security.securestring.aspx

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment