Saturday, December 03, 2011

Read Password from Console

Yesterday I was write codes to test my class for user Windows authentication. The simple console app will take user name and password as input. I would like password from console input like *** from a text box. By googling search, I found the following codes. They works as expected.

The example codes are very simple. Actually I tried to search from Console class in Visual Studio, and I found ReadKey method. I did not figure out how to get input from this method, since the keys from the methods are all in caps. Then I searched the web and found this solution. Sharing is great!

public static string ReadPassword() {
  Stack<string> passbits = new Stack<string>();
  //keep reading
  for (ConsoleKeyInfo cki = Console.ReadKey(true);
      cki.Key != ConsoleKey.Enter; cki = Console.ReadKey(true)) {
    if (cki.Key == ConsoleKey.Backspace) {
      //rollback the cursor and write a space so it looks backspaced to the user
      Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
      Console.Write(" ");
      Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
      passbits.Pop();
    }
    else {
      Console.Write("*");
      passbits.Push(cki.KeyChar.ToString());
    }
  }
  string[] pass = passbits.ToArray();
  Array.Reverse(pass);
  return string.Join(string.Empty, pass);
}

Reference

1 comments:

Anonymous said...

You can find another implementation at

http://cinchoo.wordpress.com/2012/02/07/cinchoo-read-password-from-console/