Home >Backend Development >C++ >How Can I Efficiently Delete Files and Subfolders from a Directory in C# While Preserving the Root Directory?
C# efficiently deletes files and folders in a directory
When dealing with directories, it is often necessary to delete all contents within the directory while retaining the root directory itself. This can be efficiently achieved through C#’s System.IO.DirectoryInfo class.
Method:
To delete files and subdirectories within a given directory, follow these steps:
Create DirectoryInfo object: Create a DirectoryInfo object for the target directory.
<code class="language-csharp">System.IO.DirectoryInfo di = new DirectoryInfo("YourPath");</code>
Delete files: Use GetFiles() or EnumerateFiles() to iterate over the files in a directory.
<code class="language-csharp">foreach (FileInfo file in di.GetFiles()) { file.Delete(); }</code>
For large directories, EnumerateFiles() is more efficient because it allows enumeration to occur before loading the entire collection into memory.
Delete directory: Likewise, use GetDirectories() or EnumerateDirectories() to iterate over subdirectories.
<code class="language-csharp">foreach (DirectoryInfo dir in di.GetDirectories()) { dir.Delete(true); }</code>
Recursively delete subdirectories: Setting the true parameter to Delete() ensures that all subdirectories and files within them are deleted.
The above is the detailed content of How Can I Efficiently Delete Files and Subfolders from a Directory in C# While Preserving the Root Directory?. For more information, please follow other related articles on the PHP Chinese website!