C# delete a folder and all files and folders within that folder

Viewed 186510

I'm trying to delete a folder and all files and folders within that folder, I'm using the code below and I get the error Folder is not empty, any suggestions on what I can do?

try
{
  var dir = new DirectoryInfo(@FolderPath);
  dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly;
  dir.Delete();
  dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[i].Index);
}
catch (IOException ex)
{
  MessageBox.Show(ex.Message);
}
8 Answers
dir.Delete(true); // true => recursive delete

Try:

System.IO.Directory.Delete(path,true)

This will recursively delete all files and folders underneath "path" assuming you have the permissions to do so.

The Directory.Delete method has a recursive boolean parameter, it should do what you need

Err, what about just calling Directory.Delete(path, true); ?

For those of you running into the DirectoryNotFoundException, add this check:

if (Directory.Exists(path)) Directory.Delete(path, true);
Related