Home >Backend Development >C++ >How Do I Efficiently Delete Files and Folders from a Directory in C#?

How Do I Efficiently Delete Files and Folders from a Directory in C#?

Barbara Streisand
Barbara StreisandOriginal
2025-01-11 08:38:11857browse

How Do I Efficiently Delete Files and Folders from a Directory in C#?

Removing Files and Subfolders from a Directory in C#

This guide demonstrates how to effectively remove all files and subfolders within a specified directory in C#, leaving the root directory intact.

Basic Deletion Method:

The following code provides a straightforward approach:

<code class="language-csharp">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>

Enhanced Efficiency for Large Directories:

For directories containing a substantial number of files and folders, utilizing EnumerateFiles() and EnumerateDirectories() significantly improves performance. These methods avoid loading the entire directory structure into memory at once, leading to faster processing:

<code class="language-csharp">foreach (FileInfo file in di.EnumerateFiles())
{
    file.Delete();
}
foreach (DirectoryInfo dir in di.EnumerateDirectories())
{
    dir.Delete(true);
}</code>

Employing EnumerateFiles() and EnumerateDirectories() is the recommended practice when dealing with large datasets to minimize memory consumption and enhance deletion speed.

The above is the detailed content of How Do I Efficiently Delete Files and Folders from a Directory in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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