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
Release: 2025-01-11 06:18:12
Original
485 people have browsed it

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");
Copy after login

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

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

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

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

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); 
}
Copy after login

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!

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