我想刪除一個包含文件和子文件夾,也包含文件的文件夾。我用過所有東西,但它不適合我。我使用下面的函數在我的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