Created
          February 26, 2014 19:08 
        
      - 
      
- 
        Save jstrassburg/9236252 to your computer and use it in GitHub Desktop. 
    Read a password from the console in C#
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | public string GetPassword() | |
| { | |
| Console.Write("Enter password: "); | |
| var password = new StringBuilder(); | |
| while (true) | |
| { | |
| var readKey = Console.ReadKey(true); | |
| if (readKey.Key == ConsoleKey.Enter) | |
| { | |
| Console.Write("\n"); | |
| break; | |
| } | |
| if (readKey.Key == ConsoleKey.Backspace) | |
| { | |
| if (password.Length > 0) | |
| { | |
| password.Remove(password.Length - 1, 1); | |
| Console.Write("\b \b"); | |
| } | |
| } | |
| else | |
| { | |
| password.Append(readKey.KeyChar); | |
| Console.Write("*"); | |
| } | |
| } | |
| return password.ToString(); | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment