How to delete a directory in C#

By FoxLearn 12/25/2024 3:11:57 AM   27
In C#, one of the simplest ways to delete a directory is by using the Directory.Delete() method from the System.IO namespace.

This method provides an easy way to remove a directory, whether it's empty or contains files and subdirectories.

1. Using Directory.Delete() to delete a directory in C#

using System.IO;

// Delete an empty directory
Directory.Delete(@"C:\dell\");

You can also use a relative path instead of an absolute path:

using System.IO;

// Delete using a relative path
Directory.Delete("data", recursive: true);

In this example, we use Directory.Delete() to delete an empty directory at the specified absolute path. The method will only work if the directory is empty, otherwise, an IOException will be thrown.

2. Delete a Directory that contains Files and Subdirectories

If the directory you're trying to delete contains files and subdirectories, you need to use the recursive flag. The recursive flag ensures that all files and subdirectories within the directory are deleted before the directory itself is removed.

using System.IO;

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

In this example, the recursive: true argument tells Directory.Delete() to delete all the contents of the directory (files and subdirectories) first before removing the directory itself. Without this flag, attempting to delete a non-empty directory would result in an exception.

Alternatively, you could choose to delete files in the directory before deleting the directory itself.

using System.IO;

string directoryPath = @"C:\Dell\Projects\";

// Delete all files in the directory first
foreach (var file in Directory.GetFiles(directoryPath))
{
    File.Delete(file);
}

// Now delete the empty directory
Directory.Delete(directoryPath);

If you attempt to use Directory.Delete() on a non-existent directory, it will throw a DirectoryNotFoundException.

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

To avoid encountering a DirectoryNotFoundException, you can first check if the directory exists using Directory.Exists() before attempting to delete it.

using System.IO;

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

try
{
    if (Directory.Exists(path))
        Directory.Delete(path);
}
catch(DirectoryNotFoundException)
{
    //The directory was deleted
}

The Directory.Delete() method in C# is an easy and efficient way to remove directories, both empty and non-empty, from your file system.