我想删除包含文件的文件夹和包含文件的子文件夹。我已经使用了所有东西,但它对我不起作用。我在我的web应用程序asp.net中使用以下函数:
var dir = new DirectoryInfo(folder_path);
dir.Delete(true);
有时会删除文件夹,有时则不删除。如果子文件夹包含文件,它只删除文件,而不删除文件夹。
答案 0 :(得分:23)
Directory.Delete(folder_path, recursive: true);
也可以获得理想的结果,并且更容易发现错误。
答案 1 :(得分:7)
这看起来是正确的: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);
}
}
答案 2 :(得分:4)
根据我的经验,最简单的方法是
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(文件名,格式)创建图像文件。
不知何故,这条辅助功能对我有用。
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 :(得分:1)
我使用Visual Basic版本,因为它允许您使用标准对话框。
https://msdn.microsoft.com/en-us/library/24t911bf(v=vs.100).aspx
答案 4 :(得分:1)
您也可以使用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.