Saeed Neamati
Saeed Neamati

Reputation: 35842

System.IO's Directory.Delete method sometimes work, but sometimes (specially in repetitive operations) says "The directory is not empty"

I have a button in my ASP.NET's web application, and when it's pushed, I simply delete the contents of a folder, and copy-paste some new fresh contents from another folder to it. Both folders are children of the root directory of this application, and everyone group has full access to this folder (just for testing purposes). To delete files and folders of the target folder, I use Directory.Delete method and I return the attributes of each file to normal before deleting it which means that no file is read-only or protected when deleted. This works smoothly. But when someone presses that button sequentially (in less than 15 seconds or so), the second time it throws an exception and shows "The directory is not empty). What should I do? I don't know what the problem is. I think it should be something related to IO of Operating System (in my case, Windows).

Upvotes: 0

Views: 800

Answers (3)

RAM
RAM

Reputation: 485

I think Directory.Delete(String, Boolean), returns before it's completed the deletion.

I've used the code below to refresh directories and the Sleep(100) is definitely being hit on occasions, but rarely on the first invocation (which corresponds to your description "specially (sic) in repetitive operation").

        String destination = Path.Combine(targetFolder, Name);
        if (Directory.Exists(destination))
        {
            Directory.Delete(destination, true);

            Int32 i = 0;
            while(Directory.Exists(destination))
            {
                System.Threading.Thread.Sleep(100);
                if (i++ > 50) { throw new Exception("Failed to remove " + destination); }
            }
        }
        Directory.CreateDirectory(destination);

Upvotes: 0

Saeed Neamati
Saeed Neamati

Reputation: 35842

I found the problem. I was trying to delete a read-only folder. Unfortunately, seems that .NET is not smart enough to show a relevant message.

However, always before copying, moving, or deleting any file or folder, set its attribute to normal:

File.SetAttributes(filePath, FileAttributes.Normal);

Upvotes: 0

Jude Cooray
Jude Cooray

Reputation: 19872

Use the overloaded method, Directory.Delete(directoryToDelete, true);

Take a look at this method.

It says

Deletes the specified directory and, if indicated, any subdirectories and files in the directory.

The Directory.Delete method you are using requires the directory to be empty.

Update

This question is asked here before.

Cannot delete directory with Directory.Delete(path, true)

Upvotes: 1

Related Questions