Directory.EnumerateFiles vs Directory.Delete

Dani_S 4,461 Reputation points
2025-04-15T03:40:05.44+00:00

Hi,

Are this code:

var dir = new DirectoryInfo(viewDeviceItem.Path);

dir.Delete(true);

Equivalent to:

using System;

using System.IO;

class Program

{

static void Main()

{

string directoryPath = @"C:\path\to\your\directory"; // Specify your directory path here

try

{

// Delete all files in the directory

foreach (var file in Directory.EnumerateFiles(directoryPath))

{

File.Delete(file);

}

// Delete all subdirectories in the directory

foreach (var subDirectory in Directory.EnumerateDirectories(directoryPath))

{

Directory.Delete(subDirectory, true); // true to delete subdirectories and files inside them

}

// Delete the directory itself

Directory.Delete(directoryPath, false); // false because we’ve already deleted the contents

Console.WriteLine("Directory and its contents have been deleted.");

}

catch (Exception ex)

{

Console.WriteLine($"An error occurred: {ex.Message}");

}

}

}

.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: An environment required to run apps that aren't compiled to machine language.
1,215 questions
0 comments No comments
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 74,696 Reputation points
    2025-04-16T16:07:20.43+00:00

    to delete a directory, the directory must be empty. so a recursive delete of files is required. your code is functionally the same, but it uses Directory.Delete() instead of recursion (so not sure the point)

    the Directory.Delete() uses the low level windows api:

    windows:

    https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/IO/FileSystem.Windows.cs#L250

    unix:

    https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/IO/FileSystem.Unix.cs

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.