I'm prompting the user to key in his id and password in console application.
How do I hide or change the password to 'xxxxx' when the user keys in ?
Console.WriteLine("Pls key in your Login ID");
loginid = Console.ReadLine();
Console.WriteLine("Pls key in your Password");
password = Console.ReadLine();
if (loginname == "123456" && password == "abcdef")
Loading

AlanRank #669 · 3.6K reputationPosted Jul 21, 2007, 10:32 AM EDT
using System.Text; // as we're using StringBuilder
.........
Console.WriteLine("Pls key in your Login ID");
loginid = Console.ReadLine();
Console.WriteLine("Pls key in your Password");
StringBuilder sb = new StringBuilder();
char key;
while ((key = Console.ReadKey(true).KeyChar) != '\r') // continue until return pressed
{
if (key == '\b' && sb.Length > 0) // backspace pressed after at least one char entered
{
Console.Write(key + " " + key);
sb = sb.Remove(sb.Length - 1, 1);
}
else if (Char.IsLetterOrDigit(key))
{
Console.Write("x");
sb = sb.Append(key);
}
}
Console.WriteLine();
password = sb.ToString();
Keith35 reputationPosted Jul 22, 2007, 12:04 PM EDT
Your code is great !
But whenever I key in backspace as the first character, it will still take in.
I wonder if you have anyway to avoid that ?
AlanRank #669 · 3.6K reputationPosted Jul 22, 2007, 1:30 PM EDT
I'm puzzled by that as the backspace key should only work if at least one character has already been entered i.e. the length of the StringBuilder is greater than zero. If you try to key in backspace as the first character, it shouldn't have any effect.
Are you sure you've typed the code in correctly?
zhang wenwei2 reputationPosted Jul 22, 2007, 6:12 PM EDT
i look for this for a long time
Keith35 reputationPosted Jul 25, 2007, 6:19 AM EDT
Alan,
Just tested your code and works perfectly well.
It's my code having problem, thanks cheers.