簡體   English   中英

刪除C#中特定文件夾中的文件夾和文件

[英]Delete the Folder and Files within A particular Folder in 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);
        }

它將同時刪除上載文件夾。 我只想刪除上載文件夾中的文件夾之一。

防爆。

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

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

嘗試以下代碼:

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

      }

我會這樣做:

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

我認為您需要更改為:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM