Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Directory is not empty error in c#

Tags:

c#

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?

like image 794
Searcher Avatar asked May 30 '12 12:05

Searcher


People also ask

What does the directory is not empty mean?

What is error 0x80070091 The directory is not empty? It mainly occurs when you try to delete a folder from an external hard disk or SD card or pen drive, but it can also happen when deleting a file from the system drive.

What is the meaning of empty directory?

An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “ . ” and almost every directory contains “ .. ” (except for a root directory); an empty directory contains no other entries.


2 Answers

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.

like image 194
FishBasketGordo Avatar answered Nov 15 '22 00:11

FishBasketGordo


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

like image 21
MrSoundless Avatar answered Nov 14 '22 23:11

MrSoundless