2014-04-25 107 views
1

如何刪除C#中特定文件夾內的文件夾及其文件?刪除C#中特定文件夾內的文件夾和文件

當我嘗試運行此代碼:

 try{ 
      var dir = new DirectoryInfo(@"uploads//"+civil_case.Text); 
      dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly; 
      dir.Delete(true); 
     } 
     catch (IOException ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 

還將刪除上傳的文件夾。我只想刪除上傳文件夾中的一個文件夾。

Ex。

 Uploads > 
       1stfolder > 
         > content 1.pdf 
         > content 2.png 
       2ndfolder > 
         > content 1.pdf 
         > content 2.png 

我想刪除1stfolder但事實證明它刪除該文件夾Uploads過。

+0

是什麼'civil_case。 Text'? '1stfolder' –

+0

civil_case.Text是我捕獲要刪除的文件夾的名稱。例如那個是1stfolder。 – user3569641

回答

0

試試下面的代碼:

 try { 
     string[] myFilePaths = Directory.GetFiles(@"uploads//" +civil_case.Text); 
     foreach (string file_path in myFilePaths) 
     File.Delete(file_path); 
     } 
     catch { 

     } 
+0

它不會刪除任何內容。 – user3569641

0

我會做這樣的:

try 
    { 
     var dir = new DirectoryInfo(@"uploads//"+civil_case.Text); 
     dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly; 


     //delete  
     System.IO.Directory.Delete(@"uploads//"+civil_case.Text, true); 

    } 
    catch (IOException ex) 
    { 
     MessageBox.Show(ex.Message); 
    } 
+0

訪問路徑被拒絕 – user3569641

+0

@ user3569641:也許現在?我做了一個編輯 – JoJo

0

我認爲你需要更改爲:

try{ 

     var dir = new DirectoryInfo(@"uploads\") ; //change the // to \ 
     foreach (DirectoryInfo subDir in dir) 
     { 
      If(subDir.FullName.Contains(civil_case.Text)) 
      { 
       subDir.Attributes = subDir.Attributes & ~FileAttributes.ReadOnly; 
       subDir.Delete(true); 

      } 
     } 
      } 
    catch (IOException ex) 
    { 
     MessageBox.Show(ex.Message); 
    } 
+0

它也刪除了'uploads'文件夾。 – user3569641

+0

字符串不包含定義格式.. – user3569641

+0

無法刪除。目錄不爲空 – user3569641

相關問題