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!