Created
June 23, 2016 08:14
-
-
Save philippwiddra/313796d08c7af2e1b885cc77cc16249a to your computer and use it in GitHub Desktop.
Simple function to let the user enter a password for C# console applications.
This file contains 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
static string ConsoleReadPassword() | |
{ | |
StringBuilder stringBuilder = new StringBuilder(); | |
ConsoleKeyInfo keyInfo = Console.ReadKey(true); | |
while (keyInfo.Key != ConsoleKey.Enter) | |
{ | |
if (keyInfo.Key == ConsoleKey.Backspace) | |
{ | |
stringBuilder.Remove(stringBuilder.Length - 1, 1); | |
Console.CursorLeft = Console.CursorLeft - 1; | |
Console.Write(" "); | |
Console.CursorLeft = Console.CursorLeft - 1; | |
} | |
else if (!char.IsControl(keyInfo.KeyChar)) | |
{ | |
Console.Write("*"); | |
stringBuilder.Append(keyInfo.KeyChar); | |
} | |
keyInfo = Console.ReadKey(true); | |
} | |
Console.Write("\n"); | |
return stringBuilder.ToString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment