我想删除一个包含文件和子文件夹,也包含文件的文件夹。我用过所有东西,但它不适合我。我使用下面的函数在我的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(folder_path,recursive:true); ? – 2015-03-05 13:06:06
Directory.Delete(folder_path, recursive: true);
也将得到你想要的结果和很多更容易捕捉错误。
我使用Visual Basic版本,因为它允许您使用标准对话框。
https://msdn.microsoft.com/en-us/library/24t911bf(v=vs.100).aspx
您也可以通过使用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.
在我的经验,最简单的方法是这样的
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;
}
如果土特产品使用七/ Vista中,有时你不能删除文件夹,如果Explorer是一个文件夹(或更深)开放 – Stecya 2011-02-23 15:04:21
@ Stecya:我用这个作为一个Web应用程序。 – safi 2011-02-23 15:05:25
是否生成/记录了错误消息,或者删除是否仅仅是失败而已? – FrustratedWithFormsDesigner 2011-02-23 15:05:57