kjcain
5/16/2016 - 5:12 PM

Securely get a string from console

Securely get a string from console

/// <summary>
/// Reads input without writing out the characters entered
/// </summary>
private static string SecureReadLine()
{
    bool ShowAst = true;
    String input = "";
    ConsoleKeyInfo key;
    do
    {
        key = Console.ReadKey(true);
        if (key.Key != ConsoleKey.Enter && key.Key != ConsoleKey.Backspace)
        {
            input += key.KeyChar;
            if (ShowAst)
                Console.Write("*");
        }
        else
        {
            if (key.Key == ConsoleKey.Backspace && input.Length > 0)
            {
                input = input.Substring(0, (input.Length - 1));
                if (ShowAst)
                    Console.Write("\b \b");
            }
        }
    }
    while (key.Key != ConsoleKey.Enter);
    return input;
}