如何删除目录中的所有文件和文件夹?
使用C#,我如何从一个目录中删除所有的文件和文件夹,但仍然保持根目录?
System.IO.DirectoryInfo di = new DirectoryInfo("YourPath"); foreach (FileInfo file in di.GetFiles()) { file.Delete(); } foreach (DirectoryInfo dir in di.GetDirectories()) { dir.Delete(true); }
是的,这是正确的方法。 如果你想给自己一个“清洁”(或者,我喜欢称之为“空”function),你可以创build一个扩展方法。
public static void Empty(this System.IO.DirectoryInfo directory) { foreach(System.IO.FileInfo file in directory.GetFiles()) file.Delete(); foreach(System.IO.DirectoryInfo subDirectory in directory.GetDirectories()) subDirectory.Delete(true); }
这将允许你做一些事情..
System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(@"C:\..."); directory.Empty();
以下代码将recursion清除文件夹:
private void clearFolder(string FolderName) { DirectoryInfo dir = new DirectoryInfo(FolderName); foreach(FileInfo fi in dir.GetFiles()) { fi.Delete(); } foreach (DirectoryInfo di in dir.GetDirectories()) { clearFolder(di.FullName); di.Delete(); } }
我们也可以展示对LINQ的热爱:
using System.IO; using System.Linq; … var directory = Directory.GetParent(TestContext.TestDir); directory.EnumerateFiles() .ToList().ForEach(f => f.Delete()); directory.EnumerateDirectories() .ToList().ForEach(d => d.Delete(true));
请注意,我的解决scheme是不高性能的,因为我使用Get*().ToList().ForEach(...)
它生成相同的IEnumerable
两次。 我使用扩展方法来避免这个问题:
using System.IO; using System.Linq; … var directory = Directory.GetParent(TestContext.TestDir); directory.EnumerateFiles() .ForEachInEnumerable(f => f.Delete()); directory.EnumerateDirectories() .ForEachInEnumerable(d => d.Delete(true));
这是扩展方法:
/// <summary> /// Extensions for <see cref="System.Collections.Generic.IEnumerable"/>. /// </summary> public static class IEnumerableOfTExtensions { /// <summary> /// Performs the <see cref="System.Action"/> /// on each item in the enumerable object. /// </summary> /// <typeparam name="TEnumerable">The type of the enumerable.</typeparam> /// <param name="enumerable">The enumerable.</param> /// <param name="action">The action.</param> /// <remarks> /// “I am philosophically opposed to providing such a method, for two reasons. /// …The first reason is that doing so violates the functional programming principles /// that all the other sequence operators are based upon. Clearly the sole purpose of a call /// to this method is to cause side effects.” /// —Eric Lippert, “foreach” vs “ForEach” [http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx] /// </remarks> public static void ForEachInEnumerable<TEnumerable>(this IEnumerable<TEnumerable> enumerable, Action<TEnumerable> action) { foreach (var item in enumerable) { action(item); } } }
new System.IO.DirectoryInfo(@"C:\Temp").Delete(true); //Or System.IO.Directory.Delete(@"C:\Temp", true);
最简单的方法是:
Directory.Delete(path,true); Directory.CreateDirectory(path);
请注意,这可能会清除文件夹上的某些权限。
基于hiteshbiblog,您可能应该确保该文件是可读写的。
private void ClearFolder(string FolderName) { DirectoryInfo dir = new DirectoryInfo(FolderName); foreach (FileInfo fi in dir.GetFiles()) { fi.IsReadOnly = false; fi.Delete(); } foreach (DirectoryInfo di in dir.GetDirectories()) { ClearFolder(di.FullName); di.Delete(); } }
System.IO.Directory.Delete(installPath, true); System.IO.Directory.CreateDirectory(installPath);
我尝试过的每一种方法,在System.IO错误的某个时候都失败了。 以下方法可以正常工作,即使文件夹是空的或不是只读的,等等。
ProcessStartInfo Info = new ProcessStartInfo(); Info.Arguments = "/C rd /s /q \"C:\\MyFolder""; Info.WindowStyle = ProcessWindowStyle.Hidden; Info.CreateNoWindow = true; Info.FileName = "cmd.exe"; Process.Start(Info);
在Windows 7中,如果您刚刚使用Windows资源pipe理器手动创build它,目录结构与此类似:
C: \AAA \BBB \CCC \DDD
并且运行原始问题中build议的代码来清理目录C:\ AAA,当尝试删除BBB时,行di.Delete(true)
总是失败,IOException“目录不为空”。 这可能是由于Windows资源pipe理器中的某种延迟/caching。
以下代码可靠地为我工作:
static void Main(string[] args) { DirectoryInfo di = new DirectoryInfo(@"c:\aaa"); CleanDirectory(di); } private static void CleanDirectory(DirectoryInfo di) { if (di == null) return; foreach (FileSystemInfo fsEntry in di.GetFileSystemInfos()) { CleanDirectory(fsEntry as DirectoryInfo); fsEntry.Delete(); } WaitForDirectoryToBecomeEmpty(di); } private static void WaitForDirectoryToBecomeEmpty(DirectoryInfo di) { for (int i = 0; i < 5; i++) { if (di.GetFileSystemInfos().Length == 0) return; Console.WriteLine(di.FullName + i); Thread.Sleep(50 * i); } }
下面的代码将清理目录,但在那里保留根目录(recursion)。
Action<string> DelPath = null; DelPath = p => { Directory.EnumerateFiles(p).ToList().ForEach(File.Delete); Directory.EnumerateDirectories(p).ToList().ForEach(DelPath); Directory.EnumerateDirectories(p).ToList().ForEach(Directory.Delete); }; DelPath(path);
使用File和Directory而不是FileInfo和DirectoryInfo的静态方法会更快。 (请参阅C#中File和FileInfo的区别是什么? )。 答案显示为实用方法。
public static void Empty(string directory) { foreach(string fileToDelete in System.IO.Directory.GetFiles(directory)) { System.IO.File.Delete(fileToDelete); } foreach(string subDirectoryToDeleteToDelete in System.IO.Directory.GetDirectories(directory)) { System.IO.Directory.Delete(subDirectoryToDeleteToDelete, true); } }
string directoryPath = "C:\Temp"; Directory.GetFiles(directoryPath).ToList().ForEach(File.Delete); Directory.GetDirectories(directoryPath).ToList().ForEach(Directory.Delete);
此版本不使用recursion调用,并解决只读问题。
public static void EmptyDirectory(string directory) { // First delete all the files, making sure they are not readonly var stackA = new Stack<DirectoryInfo>(); stackA.Push(new DirectoryInfo(directory)); var stackB = new Stack<DirectoryInfo>(); while (stackA.Any()) { var dir = stackA.Pop(); foreach (var file in dir.GetFiles()) { file.IsReadOnly = false; file.Delete(); } foreach (var subDir in dir.GetDirectories()) { stackA.Push(subDir); stackB.Push(subDir); } } // Then delete the sub directories depth first while (stackB.Any()) { stackB.Pop().Delete(); } }
使用DirectoryInfo的GetDirectories方法。
foreach (DirectoryInfo subDir in new DirectoryInfo(targetDir).GetDirectories()) subDir.Delete(true);
这不是解决上述问题的最好方法。 但是这是一个替代…
while (Directory.GetDirectories(dirpath).Length > 0) { //Delete all files in directory while (Directory.GetFiles(Directory.GetDirectories(dirpath)[0]).Length > 0) { File.Delete(Directory.GetFiles(dirpath)[0]); } Directory.Delete(Directory.GetDirectories(dirpath)[0]); }
private void ClearFolder(string FolderName) { DirectoryInfo dir = new DirectoryInfo(FolderName); foreach (FileInfo fi in dir.GetFiles()) { fi.IsReadOnly = false; fi.Delete(); } foreach (DirectoryInfo di in dir.GetDirectories()) { ClearFolder(di.FullName); di.Delete(); } }
DirectoryInfo Folder = new DirectoryInfo(Server.MapPath(path)); if (Folder .Exists) { foreach (FileInfo fl in Folder .GetFiles()) { fl.Delete(); } Folder .Delete(); }
using System; using System.IO; namespace DeleteFoldersAndFilesInDirectory { class Program { public static void DeleteAll(string path) { string[] directories = Directory.GetDirectories(path); string[] files = Directory.GetFiles(path); foreach (string x in directories) Directory.Delete(x, true); foreach (string x in files) File.Delete(x); } static void Main() { Console.WriteLine("Enter The Directory:"); string directory = Console.ReadLine(); Console.WriteLine("Deleting all files and directories ..."); DeleteAll(directory); Console.WriteLine("Deleted"); } } }
这将显示我们如何删除文件夹,并检查它,我们使用文本框
using System.IO; namespace delete_the_folder { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Deletebt_Click(object sender, EventArgs e) { //the first you should write the folder place if (Pathfolder.Text=="") { MessageBox.Show("ples write the path of the folder"); Pathfolder.Select(); //return; } FileAttributes attr = File.GetAttributes(@Pathfolder.Text); if (attr.HasFlag(FileAttributes.Directory)) MessageBox.Show("Its a directory"); else MessageBox.Show("Its a file"); string path = Pathfolder.Text; FileInfo myfileinf = new FileInfo(path); myfileinf.Delete(); } } }
using System.IO; string[] filePaths = Directory.GetFiles(@"c:\MyDir\"); foreach (string filePath in filePaths) File.Delete(filePath);
从主呼叫
static void Main(string[] args) { string Filepathe =<Your path> DeleteDirectory(System.IO.Directory.GetParent(Filepathe).FullName); }
添加这个方法
public static void DeleteDirectory(string path) { if (Directory.Exists(path)) { //Delete all files from the Directory foreach (string file in Directory.GetFiles(path)) { File.Delete(file); } //Delete all child Directories foreach (string directory in Directory.GetDirectories(path)) { DeleteDirectory(directory); } //Delete a Directory Directory.Delete(path); } }
foreach (string file in System.IO.Directory.GetFiles(path)) { System.IO.File.Delete(file); } foreach (string subDirectory in System.IO.Directory.GetDirectories(path)) { System.IO.Directory.Delete(subDirectory,true); }
要删除文件夹,这是使用文本框和using System.IO;
的button的代码using System.IO;
:
private void Deletebt_Click(object sender, EventArgs e) { System.IO.DirectoryInfo myDirInfo = new DirectoryInfo(@"" + delete.Text); foreach (FileInfo file in myDirInfo.GetFiles()) { file.Delete(); } foreach (DirectoryInfo dir in myDirInfo.GetDirectories()) { dir.Delete(true); } }
以下示例显示了如何做到这一点。 它首先创build一些目录和文件,然后通过Directory.Delete(topPath, true);
删除它们Directory.Delete(topPath, true);
:
static void Main(string[] args) { string topPath = @"C:\NewDirectory"; string subPath = @"C:\NewDirectory\NewSubDirectory"; try { Directory.CreateDirectory(subPath); using (StreamWriter writer = File.CreateText(subPath + @"\example.txt")) { writer.WriteLine("content added"); } Directory.Delete(topPath, true); bool directoryExists = Directory.Exists(topPath); Console.WriteLine("top-level directory exists: " + directoryExists); } catch (Exception e) { Console.WriteLine("The process failed: {0}", e.Message); } }
它来自https://msdn.microsoft.com/en-us/library/fxeahc5f(v=vs.110).aspx 。
private void ClearDirectory(string path) { if (Directory.Exists(path))//if folder exists { Directory.Delete(path, true);//recursive delete (all subdirs, files) } Directory.CreateDirectory(path);//creates empty directory }
你应该做的唯一的事情是将optional recursive parameter
设置为True
。
Directory.Delete("C:\MyDummyDirectory", True)
感谢.NET。 🙂
IO.Directory.Delete(HttpContext.Current.Server.MapPath(path), True)
你不需要比这更多