2012-04-26 82 views
0

好的,這裏是我正在處理的代碼。我試圖得到一個例外,如果他們沒有在盒子中保存它會彈出一個例外,不讓他們繼續前進,直到把東西放在那裏。現在我知道,當我運行我的程序,然後點擊保存按鈕,它告訴我這如何輸入和例外

ArgumentException的是未處理的

是什麼意思。我知道它說空路徑名稱是不合法的。但是路徑是用戶想要的。我一直在搞這個,並試圖找出要做什麼,但仍有點困惑。那麼嘗試去實現它的最好方法是什麼?我是否必須創建一個類才能工作,或者只需將其添加到我的代碼中。我用另一個部分修正了其他部分,但是我無法在這部分工作,或者我可能把它放在了錯誤的地方。

private void Save_Click(object sender, EventArgs e) 
{ 
    string path = txtFilePath.Text;  

    if (!File.Exists(path)) 
    { 
     using (StreamWriter sw = File.CreateText(path))   
     { 
      foreach (string lines in employeeList.Items) 
       sw.WriteLine(lines); 
     } 
     else 
     { 
      using (StreamWriter sw = File.AppendText(path))<--This is 
where is says Arugment exception was unhandled.    
      {  
       foreach (var item in employeeList.Items) 
        sw.WriteLine(item.ToString()); 
      } 
     } 
    } 
} 
+0

顯示你的路徑文件 – Mediator 2012-04-26 12:19:04

+0

爲什麼不若(File.Exists(路徑)),而不是如果(!File.Exists(路徑)) ? – Hari 2012-04-26 12:23:03

回答

0

包裹在一個try catch語句,並在抓住你可以生成一個消息給用戶(也許一個JavaScript警告框)

僞碼的代碼...

try 
{ 
    current code 
} 
catch (exception e) 
{ 
    error message to user 
} 
0

使用

private void Save_Click(object sender, EventArgs e) 
{ 
    if (!string.IsNullorEmpty(txtFilePath.Text)) 
    { 
    MessageBox.Show("Please enter new path"); 
    txtFilePath.Focus(); 
    return; 
    } 
    else 
    { 
    string path = txtFilePath.Text; 

     if (!File.Exists(path)) 
     { 
      ..... Your rest code 
+0

那麼當你走這條路線時,它會發出IsNullorEmpty部分頂部的錯誤。 – shan 2012-04-26 12:49:56

+0

@Nikhil Agrawal:你錯過了其他的支架...... – 2012-04-26 13:00:57

+0

@shan:感謝Buddy。更正它。 – 2012-04-26 13:09:30

0

這意味着:

路徑是一個零長度字符串,僅包含空白,或包含 一個或多個無效字符由InvalidPathChars所限定。

0
if(path == "") 
{ 
    // Alert user or throw Exception 
} 
0

我知道這是一箇舊帖子,但我想我會回答。

上述代碼的所有錯誤是,有一個}在錯誤的地方。

If (not file exists) 
{ 

    else 
    { 
    } 
} 

其他的應該會進一步下降。

if(not file exists) 
{ 
} 
else 
{ 
}