How to delete all files and folders in C# while keeping the root directory
Question:
How to delete all files and folders under a specific directory in C# while retaining the root directory itself?
Solution:
For this you can use the System.IO.DirectoryInfo
class in C#. Here’s how to do it:
<code class="language-csharp">// 为目标目录创建一个 DirectoryInfo 对象 System.IO.DirectoryInfo di = new DirectoryInfo("YourPath"); // 遍历目录中的所有文件并删除它们 foreach (FileInfo file in di.GetFiles()) { file.Delete(); } // 遍历目录中的所有子目录并递归删除它们 foreach (DirectoryInfo dir in di.GetDirectories()) { dir.Delete(true); }</code>
Optimization:
If the directory contains a large number of files, you can use EnumerateFiles()
and EnumerateDirectories()
instead of GetFiles()
and GetDirectories()
. This is potentially more efficient as it allows you to start enumerating the collection before the collection is fully loaded into memory.
<code class="language-csharp">// 遍历目录中的所有文件并删除它们 foreach (FileInfo file in di.EnumerateFiles()) { file.Delete(); } // 遍历目录中的所有子目录并递归删除它们 foreach (DirectoryInfo dir in di.EnumerateDirectories()) { dir.Delete(true); }</code>
This optimization is especially useful when working with large directories and can improve performance. Note that there is no clear advantage to using GetFiles()
and GetDirectories()
for this problem.
The above is the detailed content of How to Delete All Files and Folders in a Directory While Keeping the Directory Itself in C#?. For more information, please follow other related articles on the PHP Chinese website!