8

In my example I am trying to delete the folders under a particular folder. My folder structure like this... C:\Export\MyDir1\MyDir2\MyDir3\MyDir4\MyDir5 This structure will come on the fly. Next time when I run my application it should check for C:\Export\MyDir1 directory and delete if exists. I written like this

private static string getExportPath(string exportTargetPath, string parentIssue)
        {
            string exportPath = Path.Combine(exportTargetPath, parentIssue);
            if (Directory.Exists(exportPath))
            {
                string[] files = Directory.GetFiles(exportPath);
                string[] dirs = Directory.GetDirectories(exportTargetPath);

                File.SetAttributes(exportTargetPath, FileAttributes.Normal);
                Directory.Delete(exportTargetPath,false);
            }

            return exportPath;
        }

I checked with the issue posted in this sit Issue I tried with this one but can't get solution. As per the suggested answer for this question, when i try to iterate through the directories then it is going to infinite loop. Where I done the mistake? Could any one help me?

Community
  • 1
  • 1
Searcher
  • 1,845
  • 9
  • 32
  • 45
  • possible duplicate of [delete a directory having subdirectory (not empty)](http://stackoverflow.com/questions/5933764/delete-a-directory-having-subdirectory-not-empty) – nawfal Feb 10 '14 at 07:49

2 Answers2

20

Do a recursive delete: Directory.Delete(exportTargetPath, true);

MSDN specifically says that you will get an IOException if:

The directory specified by path is read-only, or recursive is false and path is not an empty directory.

FishBasketGordo
  • 22,904
  • 4
  • 58
  • 91
6

The 2nd param of Directory.Delete is named 'recursive' for a reason. Try setting that to true.

MrSoundless
  • 1,246
  • 2
  • 12
  • 34
  • 1
    None of you guys are answering the question. In my case it works recursively sometimes and other times it don't. I just want to delete everything in a directory, file/folder/directory, just all! – Bojangles Sep 29 '13 at 07:49
  • How is this not an answer? Did you try it? What is the part we're missing? Enlighten us – MrSoundless Sep 30 '13 at 12:06
  • Seems like Directory class doesn't like that you to have File Explorer opened on the same path you are working on, maybe that was the problem. – mkstyl3 Sep 20 '20 at 10:35