Monday, May 3, 2010

Non-Echoing Console Input

I recently stumbled upon the need to create a small console application that reads in a password from the user. Naturally, I didn't want the password to be echoed back into the console as it was typed, luckily there's a static method called ReadKey in the Console class, but in order to read a whole string, some acrobatics is required:

string ReadPassword()
{
    string passwordString;
    List<char> chList = new List<char>();
    ConsoleKeyInfo cki = Console.ReadKey(true);
    while (cki.Key != ConsoleKey.Enter)
    {
        if (cki.Key == ConsoleKey.Backspace)
        {
            if (chList.Count > 0)
                chList.RemoveAt(chList.Count - 1);
        }
        else
            chList.Add(cki.KeyChar);
        cki = Console.ReadKey(true);
    }
    passwordString = new string(chList.ToArray());
    return passwordString;
}

No comments:

Post a Comment