2012-12-13 128 views
1

我讓這段代碼清空了一些我經常刪除的文件,比如Windows中的臨時文件。幾個朋友可能希望使用相同的應用程序,我正在處理文件未找到異常的最佳方式。處理文件未找到異常?

如何最好地處理多個用戶的使用?

public void Deletefiles() 
    { 
     try 
     {     
      string[] DirectoryList = Directory.GetDirectories("C:\\Users\\user\\Desktop\\1"); 
      string[] FileList = Directory.GetFiles("C:\\Users\\user\\Desktop\\1"); 

      foreach (string x in DirectoryList) 
      { 
       Directory.Delete(x, true); 
       FoldersCounter++; 
      } 

      foreach (string y in FileList) 
      { 
       File.Delete(y); 
       FilesCounter++; 
      } 

      MessageBox.Show("Done...\nFiles deleted - " + FileList.Length + "\nDirectories deleted - " + DirectoryList.Length + "\n" + FilesCounter + "\n", "message", MessageBoxButtons.OK, MessageBoxIcon.Information); 
      } 

     catch (Exception z) 
     { 
      if (z.Message.Contains("NotFound")) 
      { 
       MessageBox.Show("File Not Found"); 
      } 
      else 
      { 
       throw (z); 
      } 
      //throw new FileNotFoundException(); 
     } 
    } 

回答

0

修改你的代碼儘可能少的,你可以簡單地換你Delete電話在一個try/catch:

foreach (string x in DirectoryList) 
{ 
    try { 
     Directory.Delete(x, true); 
    } 
    catch (DirectoryNotFoundException e) 
    { 
     // do something, or not... 
    } 
    FoldersCounter++; 
} 

foreach (string y in FileList) 
{ 
    try 
    { 
     File.Delete(y); 
    } 
    catch (FileNotFoundException e) 
    { 
     // do something, or not... 
    } 
    FilesCounter++; 
} 

刪除頂級try/catch語句,只是讓通過foreach報表週期 - try ing和catch他們來的任何例外。

您不一定需要提醒用戶該文件未找到。它正在那裏被刪除,所以它不在那裏的事實並沒有真正影響程序的結果。

這不是最簡單的方法,但它是一個足夠簡單的應用程序,不會導致問題。

+0

是啊我不希望用戶警惕如果沒有這樣的文件,這就是我想知道如何通過使用try catch ... 沒有嘗試catch代碼將拋出一個異常......並教如果你可以請我怎麼做友好? – xXghostXx

+0

我想知道catch部分應該寫些什麼,以避免用戶在這種情況下得到異常,並讓我的程序繼續... – xXghostXx

+0

@xXghostXx聽起來你不需要在那裏寫任何東西,因爲你不會不想做任何事情。只是留下一條註釋,說明你特別想「無所事事」,所以你在將來知道爲什麼你將這個catch(FileNotFoundException e)塊留空。 –