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

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

Linda Hamilton
Linda HamiltonOriginal
2025-01-11 06:18:12595browse

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

Efficiently Deleting Files and Folders in a Directory Using C

In many scenarios, developers encounter the need to remove all files and folders from a directory while preserving the root directory. C# offers a straightforward method for accomplishing this task.

To begin, instantiate a DirectoryInfo object pointing to the target directory:

System.IO.DirectoryInfo di = new DirectoryInfo("YourPath");

Now, iterate through the files in the directory and delete each one:

foreach (FileInfo file in di.GetFiles())
{
    file.Delete(); 
}

Next, iterate through the directories in the directory and delete each one recursively:

foreach (DirectoryInfo dir in di.GetDirectories())
{
    dir.Delete(true); 
}

This approach effectively removes all files and folders from the directory, leaving only the root directory intact.

For optimal efficiency, consider utilizing EnumerateFiles() and EnumerateDirectories() instead of GetFiles() and GetDirectories(). These methods allow for incremental enumeration, avoiding the overhead of loading the entire collection into memory. The revised code using these methods:

foreach (FileInfo file in di.EnumerateFiles())
{
    file.Delete(); 
}
foreach (DirectoryInfo dir in di.EnumerateDirectories())
{
    dir.Delete(true); 
}

By employing this approach, you can efficiently delete all files and folders from a directory while preserving the root directory.

The above is the detailed content of How to 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