views:

173

answers:

2

Hi, I'm using MVC ASP.NET 3.5 and I'm trying to delete a folder with all files within using standard .NET method that I've always used in .NET 2.0.

I found this but the first answer doesn't seem to work.
I've tried this one

try
{
    Directory.Delete(path, true);
}
catch (IOException)
{
    Thread.Sleep(0);
    Directory.Delete(path, true);
}

and works, but I can't understand why.
Any suggestions?

Edit: I've got permissions, because all files and sub-folders were deleted. But I've got and Exception "Directory is non-empty" with path. If I use the code provided, works without any exceptions.

A: 

Do you have enough permissions to delete the folder? Also, as the other question says make sure that the directory is empty.

Giorgi
I've got permissions, because all files and sub-folders were deleted. But I've got and Exception "Directory is non-empty" with path.If I use the code provided, works without any exceptions.
Sig. Tolleranza
A: 

Even using the explorer this message is shown sometimes (at least for me). How about deleting the files first and then delete the folder?

string[] files = Directory.GetFiles(some_path, "", SearchOption.AllDirectories);
foreach (string pathFile in files)
{
    File.Delete(pathFile);
}
Directory.Delete(some_path);

you can use SearchOptions if you have subfolers but if not, then use simply

string[] files = Directory.GetFiles(some_path);

Hope this helps.

EDIT

This problem happens for many reasons(c'mon its MS), but I think the main are: because the folder is corrupted or some process is locking it and prevents the deletion.

A non elegant solution could be: delete the files first, then the subfolders, and the last step delete the main folder.

Argons
Your approach works, but the problem is that if you have subfolders, you have to delete them. Also, still doesn't explain the bug.
Sig. Tolleranza