[英]delete folder/files and subfolder
我想删除一个包含文件的文件夹和一个也包含文件的子文件夹。 我已经使用了所有东西,但它对我不起作用。 我在我的 web 应用程序 asp.net 中使用以下函数:
var dir = new DirectoryInfo(folder_path);
dir.Delete(true);
有时它会删除一个文件夹,有时它不会。 如果子文件夹包含文件,它只会删除该文件,而不删除文件夹。
Directory.Delete(folder_path, recursive: 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 中创建一些文件时,它最终会出现异常。 例如使用 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;
}
您也可以使用DirectoryInfo
实例方法来执行相同的操作。 我刚刚遇到了这个问题,我相信这也可以解决您的问题。
var fullfilepath = Server.MapPath(System.Web.Configuration.WebConfigurationManager.AppSettings["folderPath"]);
System.IO.DirectoryInfo deleteTheseFiles = new System.IO.DirectoryInfo(fullfilepath);
deleteTheseFiles.Delete(true);
我使用 Visual Basic 版本,因为它允许您使用标准对话框。
https://msdn.microsoft.com/en-us/library/24t911bf(v=vs.100).aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.