C# – How to delete a directory

The simplest way to delete a directory is by using Directory.Delete() (in System.IO). Here are a few examples:

using System.IO;

//Delete an empty directory

//Delete the directory and everything in it
Directory.Delete(@"C:\Projects\HelloWorld\", recursive: true);

//Delete w/ a relative path
Code language: C# (cs)

You have to specify the path of the directory to delete. This can be an absolute or relative path. You can pass in a recursive flag, which tells it to delete everything in the directory (files and subdirectories) and then delete the directory itself. Now I’ll explain how to handle a few problems when deleting directories.

Delete a directory that contains files and subdirectories

You can only delete an empty directory (otherwise you an IOException). If you’re deleting a potentially non-empty directory, pass in the recursive flag to Directory.Delete(), like this:

using System.IO;

Directory.Delete(@"C:\HelloWorld\", recursive: true);
Code language: C# (cs)

This first deletes the directory’s subdirectories and files, and then deletes the folder itself. Alternatively, you can delete the directory’s files if you want to do that separately.

Guard against DirectoryNotFoundException

If you try to use Directory.Delete() on a non-existent directory, it throws an exception:

System.IO.DirectoryNotFoundException: Could not find a part of the path

To guard against this, check if the directory exists before deleting it and catch the DirectoryNotFoundException, like this:

using System.IO;

var path = @"C:\HelloWorld\";

    if (Directory.Exists(path))
    //This means the directory was deleted
    //between calling Exists() and Delete()
    //Don't need to do anything here
Code language: C# (cs)

Just checking if the directory exists before deleting it isn’t enough. There’s a race condition: after checking if a directory exists, it could get deleted by something else. So the call to Directory.Delete() would end up throwing DirectoryNotFoundException anyway. That’s why you still need to catch the exception.

Note: Since you have to catch the exception anyway, is there any point to using Directory.Exists() here? Yes, because in general, it’s best to avoid using exceptions for flow control.

Leave a Comment