2013-06-26 43 views
-1

我的方法獲取字符串數組作爲參數,它表示我的程序必須刪除的文件和目錄的路徑。在foreach循環中,我不知道字符串是否代表文件或目錄的路徑,所以我不知道使用File.Delete()或Directory.Delete的方法。有效的方法來決定文件或目錄刪除

我創造這樣的事情,但我認爲這是可以做到更好:)

foreach (string path in deleteItems) 
     { 
      try 
      { 
       Directory.Delete(path, true); 
      } 
      catch (IOException) 
      { 
       try { File.Delete(path); } 
       catch (IOException e) { Console.WriteLine(e); } 
      } 
     } 

有人有任何想法如何做到這一點的代碼更好?

編輯:或者我認爲它可能是更好的

  if(File.Exists(path)) 
      { 
       File.Delete(path); 
       continue; 
      } 
      if(Directory.Exists(path)) 
      { 
       Directory.Delete(path); 
       continue; 
      } 
+4

查看本文[上一個問題](http://stackoverflow.c OM /問題/ 1395205 /更好的方式對檢查-IF-路徑是-A-文件或-A-目錄-C-NET)。 – Sander

回答

1

如果你想看到的字符串是否是一個文件或目錄,簡單的檢查,看它是否是使用兩個中的一個;

foreach (string path in deleteItems) 
{ 
    if(File.Exists(path)){ 
    File.Delete(path); 
    }elseif(Directory.Exists(path)){ 
    Directory.Delete(path); 
    } 
} 
+0

你有權利,我已經這樣做:) – Zabaa

+0

是的,有點想你會得出這個結論最終:) – Sander

1

正如this answer提到你應該檢查FileAttributes

foreach (string path in deleteItems) 
{ 
    FileAttributes attr = File.GetAttributes(@"c:\Temp"); 
    //detect whether its a directory or file 
    if ((attr & FileAttributes.Directory) == FileAttributes.Directory) 
     Directory.Delete(path, true); 
    else 
     File.Delete(path); 
} 

(略例外更好的可讀性處理)

0

爲什麼不使用Directory.Exists(路徑) 用於如

if(Directory.Exists(path)) 

    Directory.Delete(path); 

else 

    File.Delete(path); 
相關問題