Shahzada Shahzada - 4 days ago 6
C# Question

how to allow user to enter the password 3 times in c#?

I'm working in this program for 3 hours but i do not know where I'm doing wrong .If you could help i really appreciate it . The problem is when i'm entering the password .It says it is wrong password even if i put the right password it does not allows me to retry again .The program suppose to allows the user to try 3 times if the users puts wrong password after third time the program has to close .

public partial class UserAndPin : Window
{
public UserAndPin()
{
InitializeComponent();
}

private void btnOK_Click(object sender, RoutedEventArgs e)
{
try
{
StreamReader sr = new StreamReader("Customer.txt");

short attempts = 0;
string line;

while ((line = sr.ReadLine()) != null)
{
string[] lineArray = line.Split(';');
if (lineArray[0] == txtName.Text & lineArray[1] == pbPassword.Password)
{
MainWindow mainWindow = new MainWindow();
this.Hide();
mainWindow.ShowDialog();
//return;
}
else
{
attempts++;
if (attempts < 3)
{
MessageBox.Show("The NAME or PIN is incorect, you have " + (3 - attempts) + " attemps more");
}
if (attempts == 3)
{
MessageBox.Show("Please try again later");
this.Close();
}
}
}
sr.Close();
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}
}


}

Answer
Dictionary<string, string> loginInfo;
short attempts = 0;

public UserAndPin()
{
    InitializeComponent();

    // Load the file to the dictionary
    loginInfo = File.ReadAllLines("Customer.txt")
        .Select(i => i.Split(';')) // Lines format: Username;Password
        .ToDictionary(i => i[0].ToLower(), i => i[1]);  // Username is the key of the dictionary

}

private void btnOK_Click(object sender, RoutedEventArgs e)
{    
    var userId = txtName.Text.ToLower(); // Username ignore case
    var password = pbPassword.Password;

    if (loginInfo.ContainsKey(userId) && loginInfo[userId] == password)
    {
        // login success, show main window
        MainWindow mainWindow = new MainWindow();
        this.Hide();
        mainWindow.ShowDialog();
        return;
    }

    // login fail, increment the count only
    attempt++;

    if (attempts < 3)
    {
        MessageBox.Show("The NAME or PIN is incorect, you have " + (3 - attempts) + " attemps more");                                                    
    }
    if (attempts == 3)
    {
        MessageBox.Show("Please try again later");
        this.Close();
    }   

}
Comments