我想删除一个包含文件和子文件夹的文件夹。我已经尝试了一切,但都不起作用。在我的Web应用程序asp.net中,我正在使用以下函数:
var dir = new DirectoryInfo(folder_path);
dir.Delete(true);
有时它会删除一个文件夹,有时则不会。如果一个子文件夹包含一个文件,它只会删除文件,而不是文件夹。我想删除一个包含文件和子文件夹的文件夹。我已经尝试了一切,但都不起作用。在我的Web应用程序asp.net中,我正在使用以下函数:
var dir = new DirectoryInfo(folder_path);
dir.Delete(true);
有时它会删除一个文件夹,有时则不会。如果一个子文件夹包含一个文件,它只会删除文件,而不是文件夹。这看起来是正确的: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(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;
}
DirectoryInfo
实例方法完成相同的操作。我刚遇到这个问题,我相信这种方法也能解决您的问题。var fullfilepath = Server.MapPath(System.Web.Configuration.WebConfigurationManager.AppSettings["folderPath"]);
System.IO.DirectoryInfo deleteTheseFiles = new System.IO.DirectoryInfo(fullfilepath);
deleteTheseFiles.Delete(true);
https://msdn.microsoft.com/en-us/library/24t911bf(v=vs.100).aspx
Directory.Delete(path,recursive:true);
这段代码可以删除包含N个子文件夹和文件的文件夹。