无法将字符串写入文本文件两次

本文关键字:两次 文件 文本 字符串 | 更新日期: 2023-09-27 18:35:27

我有两个字符串,带有一个名为 eMail & password 的 C# 程序,我有一个正则表达式,可以检查文本是否匹配,如果两个字符串经过验证,它将把这两个字符串保存在 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);
        }

当我调试和测试我的程序时,只创建了一个文本文件,第一个(只有密码.txt )任何解决方案?

无法将字符串写入文本文件两次

将其

更改为:

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

因为只能执行另一个 if,在上面的代码中,如果电子邮件和密码正确,它将写入两个文件。

您无需再次检查匹配是否成功,因为您在:)之前检查了匹配是否不成功

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

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

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

您应该从代码中删除"else"

就这样