Home >Backend Development >C++ >How Can I Delete Files and Folders in C# While Keeping the Root Directory?
Delete files and folders in C# without deleting the root directory
In C#, you can delete all files and folders in a directory while retaining the root directory. This technique is useful when you need to clean directory contents without losing the directory structure.
One way is to use the DirectoryInfo
class:
<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>
This code first creates a DirectoryInfo
object for the specified path. It then uses GetFiles()
to iterate over the files in the directory and delete each one. Subsequently, it iterates over the directories using GetDirectories()
and deletes them recursively (true
parameter) to ensure all contents are deleted.
For directories containing a large number of files, in order to improve efficiency, you can use the EnumerateFiles()
and EnumerateDirectories()
methods:
<code class="language-csharp">foreach (FileInfo file in di.EnumerateFiles()) { file.Delete(); } foreach (DirectoryInfo dir in di.EnumerateDirectories()) { dir.Delete(true); }</code>
EnumerateFiles()
and EnumerateDirectories()
allow partial enumeration, making it more efficient for large directories by avoiding loading the entire collection into memory.
Both methods can achieve the goal of deleting all files and folders in the specified directory while retaining the root directory.
The above is the detailed content of How Can I Delete Files and Folders in C# While Keeping the Root Directory?. For more information, please follow other related articles on the PHP Chinese website!