1

我有兩個字符串與ac#程序名爲電子郵件&密碼,我有一個正則表達式,檢查文本是否匹配,如果兩個字符串都驗證它將保存這些在2個不同TEXTFILES兩個字符串,這是我的代碼:無法將字符串寫入文本文件兩次

 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) 任何解決方案?

+2

只有一個分支中刪除「其他」一個if/elseif/elseif將會運行。 – drch

+0

我明白了,謝謝! –

回答

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

,因爲只有一個否則,如果能夠執行,在上面的代碼中,如果電子郵件地址和密碼是否正確也將同時寫入文件。

不需要檢查是否匹配全成再次,因爲你檢查,如果它不是succesfull前:)

+1

非常感謝它現在的作品:) –

1

通過你到達那裏的時候,你知道,這兩個比賽都取得成功。只需使用:

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

你不需要寫'if' - >它肯定它是成功的匹配:) – wudzik

+0

是的,複製和粘貼錯誤 - 謝謝,糾正。 –

0

只是改變代碼的最後2「否則,如果」語句

你應該從代碼

這是所有