Home > Backend Development > C++ > How to Delete All Files and Folders in a Directory While Keeping the Directory Itself in C#?

How to Delete All Files and Folders in a Directory While Keeping the Directory Itself in C#?

Mary-Kate Olsen
Release: 2025-01-11 08:34:41
Original
305 people have browsed it

How to Delete All Files and Folders in a Directory While Keeping the Directory Itself in C#?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template