1

i have a two strings with a c# program named eMail & password and i have a regex that check if the text match or not, if the two strings are verified it will save these two strings in 2 different textfiles this is my code:

        string eMail = textBox1.Text;
        string password = textBox2.Text;
        Regex email_Regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
        Match email_Match = email_Regex.Match(eMail);
        Regex password_Regex = new Regex("^.{4,20}$");
        Match password_Match = password_Regex.Match(password);
        if (!email_Match.Success)
        {
            MessageBox.Show(this,
                "Please Enter A Valid Email Adress !",
                "Error While Connecting !",
                MessageBoxButtons.OKCancel,
                MessageBoxIcon.Error,
                MessageBoxDefaultButton.Button3);
        }
        else if (!password_Match.Success)
        {
            MessageBox.Show(this,
                "Please Enter A Valid Password !",
                "Error While Connecting !",
                MessageBoxButtons.OKCancel,
                MessageBoxIcon.Error,
                MessageBoxDefaultButton.Button3);
        }


        else if (password_Match.Success)
        {
            File.WriteAllText(@"D:\Password.txt", password);
        }

        else if (email_Match.Success)
        {
             File.WriteAllText(@"C:\Email.txt", eMail);
        }

when I debug and i test my program only one textfile is created it the first one ( only the Password.txt ) Any solution ?

3 Answers3

2

change it to:

    if (!email_Match.Success)
    {
        MessageBox.Show(this,
            "Please Enter A Valid Email Adress !",
            "Error While Connecting !",
            MessageBoxButtons.OKCancel,
            MessageBoxIcon.Error,
            MessageBoxDefaultButton.Button3);
    }
    else if (!password_Match.Success)
    {
        MessageBox.Show(this,
            "Please Enter A Valid Password !",
            "Error While Connecting !",
            MessageBoxButtons.OKCancel,
            MessageBoxIcon.Error,
            MessageBoxDefaultButton.Button3);
    }

    else
    {
       File.WriteAllText(@"D:\Password.txt", password);
       File.WriteAllText(@"C:\Email.txt", eMail);
    }

because only one else if can be executed, in code above if email and password are correct it will write to both files.

You don't need to check if match is successfull again, because you checked if it is not succesfull before :)

Kamil Budziewski
  • 22,699
  • 14
  • 85
  • 105
1

By the time you've got there, you know both matches are success. Just use:

else (password_Match.Success)
{
    File.WriteAllText(@"D:\Password.txt", password);
    File.WriteAllText(@"C:\Email.txt", eMail);
}
David M
  • 71,481
  • 13
  • 158
  • 186
0

just change the code in the last 2 "else if" statement

you should remove the "else" from the code

That's all