Home >Backend Development >C++ >How Can I Efficiently Delete Files and Subfolders from a Directory in C# While Preserving the Root Directory?

How Can I Efficiently Delete Files and Subfolders from a Directory in C# While Preserving the Root Directory?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-11 06:37:41931browse

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:

  1. Create DirectoryInfo object: Create a DirectoryInfo object for the target directory.

    <code class="language-csharp">System.IO.DirectoryInfo di = new DirectoryInfo("YourPath");</code>
  2. 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.

  3. 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!

Statement:
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