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

C#Directory

C# Problem Overview


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);
}

C# Solutions


Solution 1 - C#

dir.Delete(true); // true => recursive delete

Solution 2 - C#

Read the Manual:

Directory.Delete Method (String, Boolean)

Directory.Delete(folderPath, true);

Solution 3 - C#

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.

Solution 4 - C#

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

Solution 5 - C#

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

Solution 6 - C#

You should use:

dir.Delete(true);

for recursively deleting the contents of that folder too. See MSDN DirectoryInfo.Delete() overloads.

Solution 7 - C#

Try this.

namespace EraseJunkFiles
{
    class Program
    {
        static void Main(string[] args)
        {
            DirectoryInfo yourRootDir = new DirectoryInfo(@"C:\somedirectory\");
            foreach (DirectoryInfo dir in yourRootDir.GetDirectories())
                    DeleteDirectory(dir.FullName, true);
        }
        public static void DeleteDirectory(string directoryName, bool checkDirectiryExist)
        {
            if (Directory.Exists(directoryName))
                Directory.Delete(directoryName, true);
            else if (checkDirectiryExist)
                throw new SystemException("Directory you want to delete is not exist");
        }
    }
}

Solution 8 - C#

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJamieView Question on Stackoverflow
Solution 1 - C#Tommy CarlierView Answer on Stackoverflow
Solution 2 - C#MorfildurView Answer on Stackoverflow
Solution 3 - C#jinsungyView Answer on Stackoverflow
Solution 4 - C#Dmitri NesterukView Answer on Stackoverflow
Solution 5 - C#Paolo TedescoView Answer on Stackoverflow
Solution 6 - C#pyrocumulusView Answer on Stackoverflow
Solution 7 - C#Rosidin BimaView Answer on Stackoverflow
Solution 8 - C#YsterView Answer on Stackoverflow