Last active
February 7, 2017 15:18
-
-
Save quexy/1428edf78202288fbb57 to your computer and use it in GitHub Desktop.
Console masking password reader
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
[System.Diagnostics.DebuggerStepThrough] | |
public static string ReadPassword(char maskChar = '*') | |
{ | |
var password = string.Empty; | |
var categories = new[] { UnicodeCategory.Control, UnicodeCategory.Format, UnicodeCategory.OtherNotAssigned, UnicodeCategory.PrivateUse, UnicodeCategory.Surrogate }; | |
for (var key = Console.ReadKey(true); key.Key != ConsoleKey.Enter; key = Console.ReadKey(true)) | |
{ | |
if (!categories.Contains(CharUnicodeInfo.GetUnicodeCategory(key.KeyChar))) | |
{ | |
password = string.Concat(password, key.KeyChar); | |
Console.Write(maskChar); | |
} | |
else if (key.Key == ConsoleKey.Backspace && password.Length > 0) | |
{ | |
password = password.Remove(password.Length - 1); | |
//Console.Write("{0} {0}", key.KeyChar); // does not handle row breaks | |
#region Console.Backspace(); | |
var left = Console.CursorLeft - 1; | |
var top = Console.CursorTop; | |
if (left < 0) | |
{ | |
left = Console.BufferWidth - 1; | |
top = top - 1; | |
} | |
Console.SetCursorPosition(left, top); | |
Console.WriteLine(" "); | |
Console.SetCursorPosition(left, top); | |
#endregion | |
} | |
} | |
Console.WriteLine(); | |
return password; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment