删除文件夹/文件和子文件夹

我想删除一个包含文件的文件夹和一个包含文件的子文件夹。 我已经使用了所有东西,但它对我不起作用。 我在我的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);

也会让你获得理想的结果,并且更容易发现错误。

根据我的经验,最简单的方法就是这样

 Directory.Delete(folderPath, true); 

但是,当我尝试在删除后立即创建相同的文件夹时,我遇到了此function的问题。

 Directory.Delete(outDrawableFolder, true); //Safety check, if folder did not exist create one if (!Directory.Exists(outDrawableFolder)) { Directory.CreateDirectory(outDrawableFolder); } 

现在,当我的代码尝试在outDrwableFolder中创建一些文件时,它最终会出现exception。 比如使用api Image.Save(文件名,格式)创建图像文件。

不知何故,这个辅助function对我有用。

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

我使用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); 

有关详细信息,请查看此链接,因为它看起来是一样的。