Click here to Skip to main content
15,888,148 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi,

I have written the code to display my password characters in "*" but it is also consediring "enter" as one character for my password. Can you please help me with this?
Below is my code:
C#
Console.Write("Enter Password :");
ConsoleKeyInfo key;String pwd="";
do
{
    key = Console.ReadKey(true);

    if (key.Key != ConsoleKey.Backspace)
    {
        pwd += key.KeyChar;
        Console.Write("*");                                    
    }

} while (key.Key != ConsoleKey.Enter);

pwd = Console.ReadLine();


Please let me know where i am going wrong.
Note:
I dont have any method or something returning the password.

Thanks in advacne.
Posted
Updated 17-Jan-13 21:48pm
v3
Comments
archies_gall 18-Jan-13 3:45am    
I used while like this:
Console.Write("Password :");
ConsoleKeyInfo key;
while (key.Key != ConsoleKey.Enter)
{
key = Console.ReadKey(true);

if (key.Key != ConsoleKey.Backspace)
{
pwd += key.KeyChar;

Console.Write("*");


}

}
pwd = Console.ReadLine();

while building i am getting error as "Use of unassigned local variable 'key'"
what value should be assigned to key? it doesnt accept null value.

use the while loop instead of do while ... it will solve your problem
 
Share this answer
 
Change your code something like this:
C#
Console.Write("Enter Password :");
ConsoleKeyInfo key; String pwd = "";
do
{
    key = Console.ReadKey(true);

    if (key.Key != ConsoleKey.Backspace && key.Key!=ConsoleKey.Enter)
    {
        pwd += key.KeyChar;
        Console.Write("*");
    }

} while (key.Key != ConsoleKey.Enter);

Console.ReadLine();
Console.WriteLine(pwd);
Console.ReadKey();

OR
If you want to use while loop assign the value of key like this:
C#
ConsoleKeyInfo key='\0';

Good Luck
Enjoy!
 
Share this answer
 
Write your code as below.

C#
Console.Write("Password :"); 
ConsoleKeyInfo key;
key=Console.ReadKey(true);
while (key.Key != ConsoleKey.Enter) 
{ 
   if (key.Key != ConsoleKey.Backspace) 
   { 
     pwd += key.KeyChar; 
     Console.Write("*"); 
   } 
   key = Console.ReadKey(true); 
} 
pwd = Console.ReadLine();


This may help you.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900