# Tutorial :Recursive delete of files and directories in C#

### Question:

how to delete a given dir recursively in C#? Should the System.IO.Directory.Delete with the second parameter true do the trick?

EDIT: I meant a directory containing files :D Sorry for the misunderstaning.

EDIT2: So, I actually did answer my own question, although the answers here were a little more clarifying. The reason for me asking this in the first place was that the code that has exactly that invocation of Delete (2nd param set to true) was not doing what it was supposed to be doing. As it turned out the cause of that was that there was a file somewhere down in the the directory hierarchy with RO attribute set, and the Polish version of Windows XP was throwing a really strange message for that.

### Solution:1

Yup, that's the point of that parameter. Did you try it and have any problems? (I've just double-checked, and it works fine for me.)

### Solution:2

The only solution that worked for me if the subdirectories also contains files is by using a recursive function:

    public static void RecursiveDelete(DirectoryInfo baseDir)      {          if (!baseDir.Exists)              return;            foreach (var dir in baseDir.EnumerateDirectories())          {              RecursiveDelete(dir);          }          baseDir.Delete(true);      }  

It appears that Directory.Delete(dir, true) only delete files of the current directory, and subdirectories if they are empty.

Hope it helps someone.

### Solution:3

Recursive works for both files and folders (oddly, I thought it didn't work for files; my bad...):

// create some nested folders...  Directory.CreateDirectory(@"c:\foo");  Directory.CreateDirectory(@"c:\foo\bar");  // ...with files...  File.WriteAllText(@"c:\foo\blap.txt", "blup");  File.WriteAllText(@"c:\foo\bar\blip.txt", "blop");  // ...and delete them  Directory.Delete(@"c:\foo", true); // fine  

### Solution:4

Why do not use?

Directory.Delete(directoryPath, true);

https://msdn.microsoft.com/en-us/library/fxeahc5f(v=vs.110).aspx

### Solution:5

If you get UnauthorizedAccessException . You can use modified of RecursiveDelete from Jone Polvora. Thank you for Idea. I will use it.

    public static void RecursiveDelete(DirectoryInfo baseDir)      {          if (!baseDir.Exists)              return;            foreach (var dir in baseDir.EnumerateDirectories())          {              RecursiveDelete(dir);          }          var files = baseDir.GetFiles();          foreach (var file in files)          {              file.IsReadOnly = false;              file.Delete();          }          baseDir.Delete();      }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »