删除文件夹/文件及其子文件夹

21

我想删除一个包含文件和子文件夹的文件夹。我已经尝试了一切,但都不起作用。在我的Web应用程序asp.net中,我正在使用以下函数:

var dir = new DirectoryInfo(folder_path);
dir.Delete(true); 
有时它会删除一个文件夹,有时则不会。如果一个子文件夹包含一个文件,它只会删除文件,而不是文件夹。

1
如果您使用Windows 7 / Vista,有时如果资源管理器打开了该文件夹(或更深的层次结构),则无法删除该文件夹。 - Stecya
@ Stecya:我正在使用它作为一个网络应用程序。 - safi
是否会产生/记录错误信息,还是删除操作会悄无声息地失败? - FrustratedWithFormsDesigner
你有收到任何异常吗?如果有,请在问题中更新详细信息。 - Fredrik Mörk
@bojanskr:目录不是空的,我想删除所有文件和子文件夹,无论它们是否为空。 - safi
显示剩余2条评论
6个回答

41

10

这看起来是正确的: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);
    }
}

1
为什么不使用 Directory.Delete(folder_path, recursive:true) 呢? - Yegor Razumovsky

7
在我的经验中,最简单的方法是这样的。
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中创建一些文件时,会遇到异常,例如使用Image.Save(filename, format) API创建图像文件。

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

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

3
您也可以使用DirectoryInfo实例方法完成相同的操作。我刚遇到这个问题,我相信这种方法也能解决您的问题。
var fullfilepath = Server.MapPath(System.Web.Configuration.WebConfigurationManager.AppSettings["folderPath"]);

System.IO.DirectoryInfo deleteTheseFiles = new System.IO.DirectoryInfo(fullfilepath);

deleteTheseFiles.Delete(true);

更多细节请查看此链接,因为它看起来是相同的。


1

0

Directory.Delete(path,recursive:true);

这段代码可以删除包含N个子文件夹和文件的文件夹。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接