Skip to content

Instantly share code, notes, and snippets.

@asadrefai
Created January 2, 2017 07:21
Show Gist options
  • Save asadrefai/45b1adaae0f65055ab78a04dfbfd32c9 to your computer and use it in GitHub Desktop.
Save asadrefai/45b1adaae0f65055ab78a04dfbfd32c9 to your computer and use it in GitHub Desktop.
c# function to mask and display password string as *
/// <summary>
/// Function to display password string as *, return appropriate one to the code.
/// </summary>
public static string ReadLineMasked(char mask = '*')
{
var sb = new StringBuilder();
ConsoleKeyInfo keyInfo;
while ((keyInfo = Console.ReadKey(true)).Key != ConsoleKey.Enter)
{
if (!char.IsControl(keyInfo.KeyChar))
{
sb.Append(keyInfo.KeyChar);
Console.Write(mask);
}
else if (keyInfo.Key == ConsoleKey.Backspace && sb.Length > 0)
{
sb.Remove(sb.Length - 1, 1);
if (Console.CursorLeft == 0)
{
Console.SetCursorPosition(Console.BufferWidth - 1, Console.CursorTop - 1);
Console.Write(' ');
Console.SetCursorPosition(Console.BufferWidth - 1, Console.CursorTop - 1);
}
else Console.Write("\b \b");
}
}
Console.WriteLine();
return sb.ToString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment