Normally in a Winform application, a TextBox is used for users to type in their password and it's very easy to mask the typed in password by setting the TextBox.PasswordChar property to whatever character you want to used as the mask. However, in a console application, it's not so simple. For each keystroke, we have to read the ConsoleKeyInfo, save the character, wipe out what the use just typed on screen to replace it with a password mask character.

This little function does just that.

vb.net Code:
  1. Private Function GetPassword(Optional ByVal passwordMask As Char = "*"c) As String
  2.         Dim pwd As String = String.Empty
  3.         Dim sb As New System.Text.StringBuilder()
  4.         Dim cki As ConsoleKeyInfo = Nothing
  5.  
  6.         'Get the password
  7.         Console.Write("Enter password: ")
  8.         While (True)
  9.             While Console.KeyAvailable() = False
  10.                 System.Threading.Thread.Sleep(50)
  11.             End While
  12.             cki = Console.ReadKey(True)
  13.             If cki.Key = ConsoleKey.Enter Then
  14.                 Console.WriteLine()
  15.                 Exit While
  16.             ElseIf cki.Key = ConsoleKey.Backspace Then
  17.                 If sb.Length > 0 Then
  18.                     sb.Length -= 1
  19.                     Console.Write(ChrW(8) & ChrW(32) & ChrW(8))
  20.                 End If
  21.                 Continue While
  22.             ElseIf Asc(cki.KeyChar) < 32 OrElse Asc(cki.KeyChar) > 126 Then
  23.                 Continue While
  24.             End If
  25.             sb.Append(cki.KeyChar)
  26.             Console.Write(passwordMask)
  27.         End While
  28.         pwd = sb.ToString()
  29.         Return pwd
  30.     End Function