开发者

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).


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)


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜