Home >Backend Development >C++ >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!