[C#][转载]如何删除目录中的所有文件和文件夹

深碍√TFBOYSˉ_ 2022-08-28 10:53 399阅读 0赞

使用C#,如何从目录中删除所有文件和文件夹,但仍保留根目录?

29个解决方案

657 votes

  1. System.IO.DirectoryInfo di = new DirectoryInfo("YourPath");
  2. foreach (FileInfo file in di.GetFiles())
  3. {
  4. file.Delete();
  5. }
  6. foreach (DirectoryInfo dir in di.GetDirectories())
  7. {
  8. dir.Delete(true);
  9. }

如果您的目录可能包含许多文件,则GetFiles()GetDirectories()更有效,因为当您使用EnumerateFiles()时,您可以在返回整个集合之前开始枚举它,而不是GetFiles(),您需要在开始枚举之前将整个集合加载到内存中 它。 在这里看到这个引用:

因此,当您使用许多文件和目录时,EnumerateFiles()可以更有效。

这同样适用于GetFiles()GetDirectories().因此代码将是:

  1. foreach (FileInfo file in di.EnumerateFiles())
  2. {
  3. file.Delete();
  4. }
  5. foreach (DirectoryInfo dir in di.EnumerateDirectories())
  6. {
  7. dir.Delete(true);
  8. }

出于这个问题的目的,没有理由使用GetFiles()GetDirectories()

gsharp answered 2018-12-26T10:24:56Z

162 votes

是的,这是正确的方法。 如果你想给自己一个“干净”(或者,我更喜欢称之为“清空”功能),你可以创建一个扩展方法。

  1. public static void Empty(this System.IO.DirectoryInfo directory)
  2. {
  3. foreach(System.IO.FileInfo file in directory.GetFiles()) file.Delete();
  4. foreach(System.IO.DirectoryInfo subDirectory in directory.GetDirectories()) subDirectory.Delete(true);
  5. }

这将允许你做类似的事情..

  1. System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(@"C:\...");
  2. directory.Empty();

Adam Robinson answered 2018-12-26T10:25:20Z

64 votes

以下代码将递归清除该文件夹:

  1. private void clearFolder(string FolderName)
  2. {
  3. DirectoryInfo dir = new DirectoryInfo(FolderName);
  4. foreach(FileInfo fi in dir.GetFiles())
  5. {
  6. fi.Delete();
  7. }
  8. foreach (DirectoryInfo di in dir.GetDirectories())
  9. {
  10. clearFolder(di.FullName);
  11. di.Delete();
  12. }
  13. }

hiteshbiblog answered 2018-12-26T10:25:41Z

37 votes

  1. new System.IO.DirectoryInfo(@"C:\Temp").Delete(true);
  2. //Or
  3. System.IO.Directory.Delete(@"C:\Temp", true);

Thulasiram answered 2018-12-26T10:25:56Z

36 votes

我们也可以表达对LINQ的热爱:

  1. using System.IO;
  2. using System.Linq;
  3. var directory = Directory.GetParent(TestContext.TestDir);
  4. directory.EnumerateFiles()
  5. .ToList().ForEach(f => f.Delete());
  6. directory.EnumerateDirectories()
  7. .ToList().ForEach(d => d.Delete(true));

请注意,我的解决方案不符合要求,因为我使用的是Get*().ToList().ForEach(...)两次生成相同的IEnumerable。 我使用扩展方法来避免此问题:

  1. using System.IO;
  2. using System.Linq;
  3. var directory = Directory.GetParent(TestContext.TestDir);
  4. directory.EnumerateFiles()
  5. .ForEachInEnumerable(f => f.Delete());
  6. directory.EnumerateDirectories()
  7. .ForEachInEnumerable(d => d.Delete(true));

这是扩展方法:

  1. /// <summary>
  2. /// Extensions for <see cref="System.Collections.Generic.IEnumerable"/>.
  3. /// </summary>
  4. public static class IEnumerableOfTExtensions
  5. {
  6. /// <summary>
  7. /// Performs the <see cref="System.Action"/>
  8. /// on each item in the enumerable object.
  9. /// </summary>
  10. /// <typeparam name="TEnumerable">The type of the enumerable.</typeparam>
  11. /// <param name="enumerable">The enumerable.</param>
  12. /// <param name="action">The action.</param>
  13. /// <remarks>
  14. /// “I am philosophically opposed to providing such a method, for two reasons.
  15. /// …The first reason is that doing so violates the functional programming principles
  16. /// that all the other sequence operators are based upon. Clearly the sole purpose of a call
  17. /// to this method is to cause side effects.”
  18. /// —Eric Lippert, “foreach” vs “ForEach” [http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx]
  19. /// </remarks>
  20. public static void ForEachInEnumerable<TEnumerable>(this IEnumerable<TEnumerable> enumerable, Action<TEnumerable> action)
  21. {
  22. foreach (var item in enumerable)
  23. {
  24. action(item);
  25. }
  26. }
  27. }

rasx answered 2018-12-26T10:26:25Z

29 votes

最简单的方法:

  1. Directory.Delete(path,true);
  2. Directory.CreateDirectory(path);

请注意,这可能会删除该文件夹的某些权限。

Igor Mukhachev answered 2018-12-26T10:26:51Z

24 votes

基于hiteshbiblog,您可能应该确保该文件是可读写的。

  1. private void ClearFolder(string FolderName)
  2. {
  3. DirectoryInfo dir = new DirectoryInfo(FolderName);
  4. foreach (FileInfo fi in dir.GetFiles())
  5. {
  6. fi.IsReadOnly = false;
  7. fi.Delete();
  8. }
  9. foreach (DirectoryInfo di in dir.GetDirectories())
  10. {
  11. ClearFolder(di.FullName);
  12. di.Delete();
  13. }
  14. }

如果您知道没有子文件夹,这样的事情可能是最简单的:

  1. Directory.GetFiles(folderName).ForEach(File.Delete)

zumalifeguard answered 2018-12-26T10:27:16Z

12 votes

  1. System.IO.Directory.Delete(installPath, true);
  2. System.IO.Directory.CreateDirectory(installPath);

MacGyver answered 2018-12-26T10:27:33Z

6 votes

我尝试过的每一种方法,在某些方面都出现了System.IO错误。 以下方法可以肯定,即使文件夹是空的,也可以是只读的,等等。

  1. ProcessStartInfo Info = new ProcessStartInfo();
  2. Info.Arguments = "/C rd /s /q \"C:\\MyFolder"";
  3. Info.WindowStyle = ProcessWindowStyle.Hidden;
  4. Info.CreateNoWindow = true;
  5. Info.FileName = "cmd.exe";
  6. Process.Start(Info);

Alexandru Dicu answered 2018-12-26T10:27:56Z

6 votes

以下代码将清除目录,但保留根目录(递归)。

  1. Action<string> DelPath = null;
  2. DelPath = p =>
  3. {
  4. Directory.EnumerateFiles(p).ToList().ForEach(File.Delete);
  5. Directory.EnumerateDirectories(p).ToList().ForEach(DelPath);
  6. Directory.EnumerateDirectories(p).ToList().ForEach(Directory.Delete);
  7. };
  8. DelPath(path);

hofi answered 2018-12-26T10:28:16Z

4 votes

仅使用File和Directory而不是FileInfo和DirectoryInfo的静态方法将执行得更快。 (参见C#中File和FileInfo有什么区别的接受答案?)。 答案显示为实用方法。

  1. public static void Empty(string directory)
  2. {
  3. foreach(string fileToDelete in System.IO.Directory.GetFiles(directory))
  4. {
  5. System.IO.File.Delete(fileToDelete);
  6. }
  7. foreach(string subDirectoryToDeleteToDelete in System.IO.Directory.GetDirectories(directory))
  8. {
  9. System.IO.Directory.Delete(subDirectoryToDeleteToDelete, true);
  10. }
  11. }

Kriil answered 2018-12-26T10:28:45Z

3 votes

在Windows 7中,如果您刚刚使用Windows资源管理器手动创建它,则目录结构与此类似:

  1. C:
  2. \AAA
  3. \BBB
  4. \CCC
  5. \DDD

并且运行原始问题中建议的代码来清理目录C:\ AAA,第di.Delete(true)行在尝试删除BBB时始终因IOException“目录不为空”而失败。 这可能是因为Windows资源管理器中存在某种延迟/缓存。

以下代码可靠地为我工作:

  1. static void Main(string[] args)
  2. {
  3. DirectoryInfo di = new DirectoryInfo(@"c:\aaa");
  4. CleanDirectory(di);
  5. }
  6. private static void CleanDirectory(DirectoryInfo di)
  7. {
  8. if (di == null)
  9. return;
  10. foreach (FileSystemInfo fsEntry in di.GetFileSystemInfos())
  11. {
  12. CleanDirectory(fsEntry as DirectoryInfo);
  13. fsEntry.Delete();
  14. }
  15. WaitForDirectoryToBecomeEmpty(di);
  16. }
  17. private static void WaitForDirectoryToBecomeEmpty(DirectoryInfo di)
  18. {
  19. for (int i = 0; i < 5; i++)
  20. {
  21. if (di.GetFileSystemInfos().Length == 0)
  22. return;
  23. Console.WriteLine(di.FullName + i);
  24. Thread.Sleep(50 * i);
  25. }
  26. }

farfareast answered 2018-12-26T10:29:24Z

3 votes

  1. private void ClearFolder(string FolderName)
  2. {
  3. DirectoryInfo dir = new DirectoryInfo(FolderName);
  4. foreach (FileInfo fi in dir.GetFiles())
  5. {
  6. fi.IsReadOnly = false;
  7. fi.Delete();
  8. }
  9. foreach (DirectoryInfo di in dir.GetDirectories())
  10. {
  11. ClearFolder(di.FullName);
  12. di.Delete();
  13. }
  14. }

Mong Zhu answered 2018-12-26T10:29:41Z

2 votes

  1. string directoryPath = "C:\Temp";
  2. Directory.GetFiles(directoryPath).ToList().ForEach(File.Delete);
  3. Directory.GetDirectories(directoryPath).ToList().ForEach(Directory.Delete);

AVH answered 2018-12-26T10:29:57Z

2 votes

此版本不使用递归调用,并解决了readonly问题。

  1. public static void EmptyDirectory(string directory)
  2. {
  3. // First delete all the files, making sure they are not readonly
  4. var stackA = new Stack<DirectoryInfo>();
  5. stackA.Push(new DirectoryInfo(directory));
  6. var stackB = new Stack<DirectoryInfo>();
  7. while (stackA.Any())
  8. {
  9. var dir = stackA.Pop();
  10. foreach (var file in dir.GetFiles())
  11. {
  12. file.IsReadOnly = false;
  13. file.Delete();
  14. }
  15. foreach (var subDir in dir.GetDirectories())
  16. {
  17. stackA.Push(subDir);
  18. stackB.Push(subDir);
  19. }
  20. }
  21. // Then delete the sub directories depth first
  22. while (stackB.Any())
  23. {
  24. stackB.Pop().Delete();
  25. }
  26. }

Jeppe Andreasen answered 2018-12-26T10:30:37Z

2 votes

这是我阅读所有帖子后结束的工具。确实如此

  • 删除所有可删除的内容
  • 如果某些文件仍在文件夹中,则返回false

它处理

  • 只读文件
  • 删除延迟
  • 锁定的文件

它不使用Directory.Delete,因为进程在异常时中止。

  1. /// <summary>
  2. /// Attempt to empty the folder. Return false if it fails (locked files...).
  3. /// </summary>
  4. /// <param name="pathName"></param>
  5. /// <returns>true on success</returns>
  6. public static bool EmptyFolder(string pathName)
  7. {
  8. bool errors = false;
  9. DirectoryInfo dir = new DirectoryInfo(pathName);
  10. foreach (FileInfo fi in dir.EnumerateFiles())
  11. {
  12. try
  13. {
  14. fi.IsReadOnly = false;
  15. fi.Delete();
  16. //Wait for the item to disapear (avoid 'dir not empty' error).
  17. while (fi.Exists)
  18. {
  19. System.Threading.Thread.Sleep(10);
  20. fi.Refresh();
  21. }
  22. }
  23. catch (IOException e)
  24. {
  25. Debug.WriteLine(e.Message);
  26. errors = true;
  27. }
  28. }
  29. foreach (DirectoryInfo di in dir.EnumerateDirectories())
  30. {
  31. try
  32. {
  33. EmptyFolder(di.FullName);
  34. di.Delete();
  35. //Wait for the item to disapear (avoid 'dir not empty' error).
  36. while (di.Exists)
  37. {
  38. System.Threading.Thread.Sleep(10);
  39. di.Refresh();
  40. }
  41. }
  42. catch (IOException e)
  43. {
  44. Debug.WriteLine(e.Message);
  45. errors = true;
  46. }
  47. }
  48. return !errors;
  49. }

Eric Bole-Feysot answered 2018-12-26T10:31:29Z

1 votes

使用DirectoryInfo的GetDirectories方法。

  1. foreach (DirectoryInfo subDir in new DirectoryInfo(targetDir).GetDirectories())
  2. subDir.Delete(true);

Mr_Hmp answered 2018-12-26T10:31:49Z

1 votes

以下示例显示了如何执行此操作。 它首先创建一些目录和一个文件,然后通过Directory.Delete(topPath, true);删除它们:

  1. static void Main(string[] args)
  2. {
  3. string topPath = @"C:\NewDirectory";
  4. string subPath = @"C:\NewDirectory\NewSubDirectory";
  5. try
  6. {
  7. Directory.CreateDirectory(subPath);
  8. using (StreamWriter writer = File.CreateText(subPath + @"\example.txt"))
  9. {
  10. writer.WriteLine("content added");
  11. }
  12. Directory.Delete(topPath, true);
  13. bool directoryExists = Directory.Exists(topPath);
  14. Console.WriteLine("top-level directory exists: " + directoryExists);
  15. }
  16. catch (Exception e)
  17. {
  18. Console.WriteLine("The process failed: {0}", e.Message);
  19. }
  20. }

它来自[https://msdn.microsoft.com/en-us/library/fxeahc5f(v=vs.110).aspx。\]

Salma Tofaily answered 2018-12-26T10:32:14Z

1 votes

这不是处理上述问题的最佳方式。 但它是另一种……

  1. while (Directory.GetDirectories(dirpath).Length > 0)
  2. {
  3. //Delete all files in directory
  4. while (Directory.GetFiles(Directory.GetDirectories(dirpath)[0]).Length > 0)
  5. {
  6. File.Delete(Directory.GetFiles(dirpath)[0]);
  7. }
  8. Directory.Delete(Directory.GetDirectories(dirpath)[0]);
  9. }

dsmyrnaios answered 2018-12-26T10:32:44Z

0 votes

  1. DirectoryInfo Folder = new DirectoryInfo(Server.MapPath(path));
  2. if (Folder .Exists)
  3. {
  4. foreach (FileInfo fl in Folder .GetFiles())
  5. {
  6. fl.Delete();
  7. }
  8. Folder .Delete();
  9. }

Ashok Luhach answered 2018-12-26T10:33:01Z

0 votes

  1. using System;
  2. using System.IO;
  3. namespace DeleteFoldersAndFilesInDirectory
  4. {
  5. class Program
  6. {
  7. public static void DeleteAll(string path)
  8. {
  9. string[] directories = Directory.GetDirectories(path);
  10. string[] files = Directory.GetFiles(path);
  11. foreach (string x in directories)
  12. Directory.Delete(x, true);
  13. foreach (string x in files)
  14. File.Delete(x);
  15. }
  16. static void Main()
  17. {
  18. Console.WriteLine("Enter The Directory:");
  19. string directory = Console.ReadLine();
  20. Console.WriteLine("Deleting all files and directories ...");
  21. DeleteAll(directory);
  22. Console.WriteLine("Deleted");
  23. }
  24. }
  25. }

Diaa Eddin answered 2018-12-26T10:33:17Z

0 votes

这将显示我们如何删除文件夹并检查它我们使用文本框

  1. using System.IO;
  2. namespace delete_the_folder
  3. {
  4. public partial class Form1 : Form
  5. {
  6. public Form1()
  7. {
  8. InitializeComponent();
  9. }
  10. private void Deletebt_Click(object sender, EventArgs e)
  11. {
  12. //the first you should write the folder place
  13. if (Pathfolder.Text=="")
  14. {
  15. MessageBox.Show("ples write the path of the folder");
  16. Pathfolder.Select();
  17. //return;
  18. }
  19. FileAttributes attr = File.GetAttributes(@Pathfolder.Text);
  20. if (attr.HasFlag(FileAttributes.Directory))
  21. MessageBox.Show("Its a directory");
  22. else
  23. MessageBox.Show("Its a file");
  24. string path = Pathfolder.Text;
  25. FileInfo myfileinf = new FileInfo(path);
  26. myfileinf.Delete();
  27. }
  28. }
  29. }

Abdelrhman Khalil answered 2018-12-26T10:34:11Z

0 votes

  1. using System.IO;
  2. string[] filePaths = Directory.GetFiles(@"c:\MyDir\");
  3. foreach (string filePath in filePaths)
  4. File.Delete(filePath);

SynsMasTer answered 2018-12-26T10:34:26Z

0 votes

从主要电话

  1. static void Main(string[] args)
  2. {
  3. string Filepathe =<Your path>
  4. DeleteDirectory(System.IO.Directory.GetParent(Filepathe).FullName);
  5. }

添加此方法

  1. public static void DeleteDirectory(string path)
  2. {
  3. if (Directory.Exists(path))
  4. {
  5. //Delete all files from the Directory
  6. foreach (string file in Directory.GetFiles(path))
  7. {
  8. File.Delete(file);
  9. }
  10. //Delete all child Directories
  11. foreach (string directory in Directory.GetDirectories(path))
  12. {
  13. DeleteDirectory(directory);
  14. }
  15. //Delete a Directory
  16. Directory.Delete(path);
  17. }
  18. }

sansalk answered 2018-12-26T10:34:51Z

0 votes

  1. foreach (string file in System.IO.Directory.GetFiles(path))
  2. {
  3. System.IO.File.Delete(file);
  4. }
  5. foreach (string subDirectory in System.IO.Directory.GetDirectories(path))
  6. {
  7. System.IO.Directory.Delete(subDirectory,true);
  8. }

Manish Y answered 2018-12-26T10:35:06Z

0 votes

要删除文件夹,这是使用文本框和按钮using System.IO;的代码:

  1. private void Deletebt_Click(object sender, EventArgs e)
  2. {
  3. System.IO.DirectoryInfo myDirInfo = new DirectoryInfo(@"" + delete.Text);
  4. foreach (FileInfo file in myDirInfo.GetFiles())
  5. {
  6. file.Delete();
  7. }
  8. foreach (DirectoryInfo dir in myDirInfo.GetDirectories())
  9. {
  10. dir.Delete(true);
  11. }
  12. }

Abdelrhman Khalil answered 2018-12-26T10:35:26Z

-2 votes

  1. private void ClearDirectory(string path)
  2. {
  3. if (Directory.Exists(path))//if folder exists
  4. {
  5. Directory.Delete(path, true);//recursive delete (all subdirs, files)
  6. }
  7. Directory.CreateDirectory(path);//creates empty directory
  8. }

dadziu answered 2018-12-26T10:35:42Z

-3 votes

您应该做的唯一事情是将Directory.Delete("C:\MyDummyDirectory", True)设置为True

Directory.Delete("C:\MyDummyDirectory", True)

感谢.NET。:)

LysanderM answered 2018-12-26T10:36:10Z

-4 votes

  1. IO.Directory.Delete(HttpContext.Current.Server.MapPath(path), True)

你不需要更多

转载:c# - 如何删除目录中的所有文件和文件夹? - ITranslater

发表评论

表情:
评论列表 (有 0 条评论,399人围观)

还没有评论,来说两句吧...

相关阅读