Summary: in this tutorial, you’ll learn how to delete a directory using the
static method.Directory.Delete()
Introduction to the C# Directory.Delete() static method
The
static method allows you to delete an empty directory from a specified path. Here’s the syntax of the Directory.Delete()
method:Directory.Delete()
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
method:Directory.Delete()
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
method.Directory.Delete()
1) Using C# the Directory.Delete() method to delete an empty directory
The following program demonstrates how to use the
method to delete an empty directory Directory.Delete()
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...done
Code 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
method:Directory.Delete
()
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...done
Code language: C# (cs)
Summary
- Use the
method to delete an empty directory or a directory and all of its contents like subdirectories and files.Directory.Delete()