Home > Backend Development > C++ > How Can I Delete Files and Folders in C# While Keeping the Root Directory?

How Can I Delete Files and Folders in C# While Keeping the Root Directory?

Linda Hamilton
Release: 2025-01-11 09:45:12
Original
441 people have browsed it

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>
Copy after login

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>
Copy after login

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!

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