Showing posts with label Console Application. Show all posts
Showing posts with label Console Application. Show all posts

July 22, 2014

I am building a console application that checks for username and password before proceeding. However, by default, the characters typed in console will appear which is not good as I don't want to display the password the user types in. So, how can I hide or mask the password.

In this code snippet, I will show how we could mask the password. In short, I will read through the characters entered for password and mask it using empty characters. Backspace will still work as expected. If the user hits the Enter key, it will move on for the next prompt.

  1. static void Main(string[] args)
  2. {
  3.     string username = string.Empty;
  4.     string password = string.Empty;
  5.     ConsoleKeyInfo key;
  6.  
  7.     Console.Write("username: ");
  8.     username = Console.ReadLine();
  9.  
  10.     Console.Write("password: ");
  11.  
  12.     do
  13.     {
  14.         key = Console.ReadKey(true);
  15.         if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
  16.         {
  17.             password += key.KeyChar;
  18.             Console.Write(string.Empty);
  19.         }
  20.         else
  21.         {
  22.             if (key.Key == ConsoleKey.Backspace && password.Length > 0)
  23.             {
  24.                 password = password.Substring(0, (password.Length - 1));
  25.                 Console.Write("\b \b");
  26.             }
  27.         }
  28.     }
  29.     while (key.Key != ConsoleKey.Enter);
  30.  
  31.     //Console.WriteLine(username + " : " + password);
  32.     Console.WriteLine("");
  33.     
  34.     //Console.WriteLine("Is Authenticated: " + (AuthenticateUser(username, password)).ToString());
  35.     Console.ReadLine();
  36. }
Reference: Shahed Kazi at AspNetify.com