Created
January 2, 2017 07:21
-
-
Save asadrefai/45b1adaae0f65055ab78a04dfbfd32c9 to your computer and use it in GitHub Desktop.
c# function to mask and display password string as *
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
/// <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