0

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.

Community
  • 1
  • 1
Sig. Tolleranza
  • 499
  • 9
  • 27

3 Answers3

1

Try using this it worked for me

  File.SetAttributes(DownloaddirPath & "\" & directoryName, FileAttributes.Normal)
  Directory.Delete(DownloaddirPath & "\" & directoryName, True)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Sumant
  • 163
  • 1
  • 8
1

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
  • 445
  • 1
  • 6
  • 23
  • 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 Feb 10 '10 at 15:14
0

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

Giorgi
  • 30,270
  • 13
  • 89
  • 125
  • 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 Feb 10 '10 at 09:25