C# – Delete all files in a directory

Use Directory.EnumerateFiles() to get the file paths in a directory. Then loop over the file paths and delete each file. Here’s an example:

using System.IO;

foreach(var filePath in Directory.EnumerateFiles(@"C:\HelloWorld\"))
{
    File.Delete(filePath);
}
Code language: C# (cs)

This deletes the root directory’s files without deleting the directory itself. I’ll show more examples.

Delete all files with a specific extension

Use Directory.EnumerateFiles’ searchPattern pattern to search for files with a specific extension. Here’s an example of deleting all text files (.txt extension) in a directory:

using System.IO;

foreach (var filePath in Directory.EnumerateFiles(@"C:\HelloWorld\", searchPattern: "*.txt"))
{
    File.Delete(filePath);
}
Code language: C# (cs)

Delete all files in the root directory and subdirectories

Use Directory.EnumerateFiles’ SearchOption.AllDirectories parameter to get all files from the root and subdirectories. Here’s an example of deleting all files in the directory, including ones in its subdirectories:

using System.IO;

foreach (var filePath in Directory.EnumerateFiles(@"C:\HelloWorld\", "*", SearchOption.AllDirectories))
{
    File.Delete(filePath);
}
Code language: C# (cs)

This only deletes the files. It keeps the root directory and subdirectories intact.

Note: With this overload, you have to pass in the searchPattern parameter as well. Pass in “*” to search for all files.

Delete all files and subdirectories

Delete all of a directory’s files and subdirectories in two steps:

  • Delete the subdirectories recursively with Directory.EnumerateDirectories() and Directory.Delete() (passing in the recursive flag).
  • Delete all remaining files in the root directory with Directory.EnumerateFiles() and File.Delete().

The following code shows how to do this:

using System.IO;

//Delete all subdirectories recursively
foreach(var subdirPath in Directory.EnumerateDirectories(@"C:\HelloWorld\"))
{
    Directory.Delete(subdirPath, recursive: true);
}

//Delete all files in the root directory
foreach (var filePath in Directory.EnumerateFiles(@"C:\HelloWorld\"))
{
    File.Delete(filePath);
}
Code language: C# (cs)

This deletes everything in the root directory, leaving you with an empty directory.