【问题标题】:delete folder/files and subfolder删除文件夹/文件和子文件夹
【发布时间】:2011-02-23 15:02:04
【问题描述】:

我想删除一个包含文件的文件夹和一个子文件夹,也包含文件。我已经使用了所有东西,但它对我不起作用。我在我的 web 应用程序 asp.net 中使用以下功能:

var dir = new DirectoryInfo(folder_path);
dir.Delete(true); 

有时它会删除一个文件夹,有时它不会。如果子文件夹包含一个文件,它只会删除该文件,而不是该文件夹。

【问题讨论】:

  • @Stecya:我正在使用它作为一个网络应用程序。
  • 是否产生/记录了错误消息,或者删除只是静默失败?
  • 您可能对可以从网络应用程序中删除的文件/文件夹拥有有限的权限。
  • 你有什么例外吗?如果是这样,请更新问题的详细信息。

标签: c#


【解决方案1】:

Directory.Delete(folder_path, recursive: true);

也会得到你想要的结果,并且更容易发现错误。

【讨论】:

    【解决方案2】:

    这看起来很正确:http://www.ceveni.com/2008/03/delete-files-in-folder-and-subfolders.html

    //to call the below method
    EmptyFolder(new DirectoryInfo(@"C:\your Path"))
    
    
    using System.IO; // dont forget to use this header
    
    //Method to delete all files in the folder and subfolders
    
    private void EmptyFolder(DirectoryInfo directoryInfo)
    {
        foreach (FileInfo file in directoryInfo.GetFiles())
        {       
           file.Delete();
         }
    
        foreach (DirectoryInfo subfolder in directoryInfo.GetDirectories())
        {
          EmptyFolder(subfolder);
        }
    }
    

    【讨论】:

    • 为什么不 Directory.Delete(folder_path, recursive:true); ?
    【解决方案3】:

    根据我的经验,最简单的方法是这样

    Directory.Delete(folderPath, true);
    

    但是当我尝试在删除后立即创建相同的文件夹时,我遇到了此功能的问题。

    Directory.Delete(outDrawableFolder, true);
    //Safety check, if folder did not exist create one
    if (!Directory.Exists(outDrawableFolder))
    {
        Directory.CreateDirectory(outDrawableFolder);
    }
    

    现在,当我的代码尝试在 outDrwableFolder 中创建一些文件时,它最终会出现异常。例如使用 api Image.Save(filename, format) 创建图像文件。

    不知何故,这个辅助函数对我有用。

    public static bool EraseDirectory(string folderPath, bool recursive)
    {
        //Safety check for directory existence.
        if (!Directory.Exists(folderPath))
            return false;
    
        foreach(string file in Directory.GetFiles(folderPath))
        {
            File.Delete(file);
        }
    
        //Iterate to sub directory only if required.
        if (recursive)
        {
            foreach (string dir in Directory.GetDirectories(folderPath))
            {
                EraseDirectory(dir, recursive);
            }
        }
        //Delete the parent directory before leaving
        Directory.Delete(folderPath);
        return true;
    }
    

    【讨论】:

      【解决方案4】:

      您也可以使用DirectoryInfo 实例方法来做同样的事情。我刚遇到这个问题,我相信这也可以解决您的问题。

      var fullfilepath = Server.MapPath(System.Web.Configuration.WebConfigurationManager.AppSettings["folderPath"]);
      
      System.IO.DirectoryInfo deleteTheseFiles = new System.IO.DirectoryInfo(fullfilepath);
      
      deleteTheseFiles.Delete(true);
      

      For more details have a look at this link as it looks like the same.

      【讨论】:

        【解决方案5】:

        我使用 Visual Basic 版本,因为它允许您使用标准对话框。

        https://msdn.microsoft.com/en-us/library/24t911bf(v=vs.100).aspx

        【讨论】: