C# Delete Directory

Summary: in this tutorial, you’ll learn how to delete a directory using the Directory.Delete() static method.

Introduction to the C# Directory.Delete() static method

The Directory.Delete() static method allows you to delete an empty directory from a specified path. Here’s the syntax of the Directory.Delete() method:

public static void Delete (
   string path
);Code language: C# (cs)

In this syntax, the path specifies the name of the empty directory to delete. The directory must be empty and writable.

If you want to delete a directory and all of its contents including subdirectories and files, you use an overload of the Directory.Delete() method:

public static void Delete (
   string path, 
   bool recursive
);Code language: C# (cs)

In this overload, if you set the recursive to true, the Delete() method will delete the directory specified by the path and all of its contents.

But if you set the recursive to false, the method behaves like the one without the recursive parameter.

Using Directory.Delete() method to delete a directory example

Let’s take some examples of using the Directory.Delete() method.

1) Using C# the Directory.Delete() method to delete an empty directory

The following program demonstrates how to use the Directory.Delete() method to delete an empty directory 2023 in the C:\backup directory:

using static System.Console;

string backupDir = @"C:\backup\";
var targetDir = Path.Combine(backupDir, "2023");

try
{
    Write($"Deleteing the directory {targetDir}...");
    Directory.Delete(targetDir);
    WriteLine("done");
}
catch (IOException ex)
{
    WriteLine(ex.Message);
}Code language: C# (cs)

Output:

Deleteing the directory C:\backup\2023...doneCode language: C# (cs)

2) Using C# Directory.Delete() method to delete a directory and all of its contents

The following program demonstrates how to delete directory 2023 and all subdirectories and files in directory 2023 using the Directory.Delete() method:

using static System.Console;

string backupDir = @"C:\backup\";
var targetDir = Path.Combine(backupDir, "2023");

try
{
    Write($"Deleteing the directory {targetDir} and its contents...");
    Directory.Delete(targetDir, true);
    WriteLine("done");
}
catch (IOException ex)
{
    WriteLine(ex.Message);
}Code language: C# (cs)

Output:

Deleteing the directory C:\backup\2023 and its contents...doneCode language: C# (cs)

Summary

  • Use the Directory.Delete() method to delete an empty directory or a directory and all of its contents like subdirectories and files.
Was this tutorial helpful ?