1

我有一个带有名为 eMail 和密码的 ac# 程序的两个字符串,我有一个正则表达式来检查文本是否匹配,如果这两个字符串得到验证,它将把这两个字符串保存在 2 个不同的文本文件中这是我的代码:

        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);
        }

当我调试并测试我的程序时,只创建了一个文本文件,它是第一个(只有 Password.txt)有什么解决方案吗?

4

3 回答 3

2

将其更改为:

    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);
    }

因为只有 else if 可以执行,所以在上面的代码中,如果电子邮件和密码正确,它将写入这两个文件。

不需要再次检查匹配是否成功,因为您之前检查过它是否不成功:)

于 2013-10-14T11:27:41.460 回答
1

当你到达那里时,你知道两场比赛都是成功的。只需使用:

else (password_Match.Success)
{
    File.WriteAllText(@"D:\Password.txt", password);
    File.WriteAllText(@"C:\Email.txt", eMail);
}
于 2013-10-14T11:29:41.003 回答
0

只需更改最后 2 个“else if”语句中的代码

你应该从代码中删除“else”

就这样

于 2013-10-14T12:13:01.913 回答