Read masked password in command line c#

command line

This code shows how to read a password wihtout disclosing it, by masking the characters with the *

string pass = string.Empty;
ConsoleKey key;

do
{
    var keyInfo = Console.ReadKey(intercept: true);
    key = keyInfo.Key;

    if (key == ConsoleKey.Backspace && pass.Length > 0)
    {
        Console.Write("\b \b");
        pass = pass[0..^1];
    }
    else if (!char.IsControl(keyInfo.KeyChar))
    {
        Console.Write("*");
        pass += keyInfo.KeyChar;
    }
} while (key != ConsoleKey.Enter);

Post a Comment

Previous Post Next Post