Skip to content

Instantly share code, notes, and snippets.

@quexy
Last active February 7, 2017 15:18
Show Gist options
  • Save quexy/1428edf78202288fbb57 to your computer and use it in GitHub Desktop.
Save quexy/1428edf78202288fbb57 to your computer and use it in GitHub Desktop.
Console masking password reader
[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