Given a directory, delete all files and subdirectories present in the directory using C#.

There are two variations to this problem. In the first variation, we delete all files and subdirectories from the specified directory along with the root directory. In the second variation, we delete all files and subdirectories but retain the root directory.

1. Delete the root directory

To delete the specified directory and all its subdirectories, use the Directory.Delete() method. The following example demonstrates its usage. The second argument to this method indicates whether to delete subdirectories and files.

Download Code

 
We can also use an instance of the DirectoryInfo class to delete subdirectories and files. It has the DirectoryInfo.Delete() method, which works similar to the Directory.Delete() method discussed above.

Download Code

2. Retain the root directory

To delete all files and subdirectories without deleting the directory, the idea is to loop through all files/subdirectories and individually delete them. We can use the GetFiles and GetDirectories() methods to retrieve the existing files and directories.

Download Code

 
We can also use EnumerateFiles and EnumerateDirectories() methods to enumerate over the existing files and directories. This is more efficient when working with many files and directories.

Download Code

 
This can also be done using LINQ’s ForEach() method instead of the foreach loop:

Download Code

 
Here’s an alternative method that first deletes the specified directory and all its subdirectories using the Directory.Delete() method and then re-create the directory. Note that this will permanently erase a few attributes on the root directory.

Download Code

That’s all about deleting all files and subdirectories in a directory with C#.