繁体   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