Mohammad Nadeem Mohammad Nadeem - 3 days ago 8
C# Question

Password masking console application

I tried the following code...

string pass = "";
Console.Write("Enter your password: ");
ConsoleKeyInfo key;

do
{
key = Console.ReadKey(true);

// Backspace Should Not Work
if (key.Key != ConsoleKey.Backspace)
{
pass += key.KeyChar;
Console.Write("*");
}
else
{
Console.Write("\b");
}
}
// Stops Receving Keys Once Enter is Pressed
while (key.Key != ConsoleKey.Enter);

Console.WriteLine();
Console.WriteLine("The Password You entered is : " + pass);


But this way the backspace functionality doesn't work while typing the password.
Any suggestion?

Answer

Console.Write("\b \b"); will delete the asterisk character from the screen, but you do not have any code within your else block that removes the previously entered character from your pass string variable.

Here's the relevant code portion (the if..else section) that should do what you require:

// Backspace Should Not Work
if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
{
   pass += key.KeyChar;
   Console.Write("*");
}
else
{
   if (key.Key == ConsoleKey.Backspace && pass.Length > 0)
   {
      pass = pass.Substring(0, (pass.Length - 1));
      Console.Write("\b \b");
   }
}
Comments