Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DirectoryInfo.Delete(True) Doesn't Delete When Folder Structure is Open in Windows Explorer

Assuming I have a folder structure like:

C:\MyTemp
   - MySubFolder

If I try to delete this using:

Dim path As String = "C:\MyTemp"
Dim di As System.IO.DirectoryInfo
di = System.IO.Directory.CreateDirectory(path)
di.CreateSubdirectory("MySubFolder")
di.Delete(True)

This works fine, unless I have Windows Explorer open and I'm looking at the 'MySubFolder' directory. Then I get an IOException The directory is not empty. - clicking OK dismisses this and then the folder structure is not deleted.

Any thoughts on how I can get this to perform correctly (i.e. delete), even when running this code while having the folder struture open in Windows Explorer?

like image 600
Todd Main Avatar asked Nov 05 '10 00:11

Todd Main


People also ask

Can't delete because folder is open in another program?

If the file you want to delete is in an “exe” file of a program, try closing the program first, then attempt to delete the file again. You can also try restarting your PC to close down any running programs or closing the apps that might be using the program you want to delete.

When I try to delete a folder it says it is in use?

Sometimes, you might get a message that the folder you're trying to delete is in use. To fix the problem, you need to close all applications that might be using this directory.


3 Answers

Only way you could get this to "work" 100% consistently is by nuking explorer (bad idea) or nuking the handle (also bad idea)

My recommendation would be to just handle the failure gracefully as opposed to trying this.

like image 87
Sam Saffron Avatar answered Oct 18 '22 13:10

Sam Saffron


Check out this article. IOException can be generated from an open handle to the directory: This open handle can result from enumerating directories and files which is exactly what opening in explorer does. Sounds like the actual error message is generic.

like image 45
pinkfloydx33 Avatar answered Oct 18 '22 15:10

pinkfloydx33


The best you can do is catch the error and then use handle.exe to find out which process is using the file and ask the user to close the application with options to retry or cancel.

Ever wondered which program has a particular file or directory open? Now you can find out. Handle is a utility that displays information about open handles for any process in the system. You can use it to see the programs that have a file open, or to see the object types and names of all the handles of a program.

Some more info here:

How to monitor process' IO activity using C#?

like image 26
Samuel Neff Avatar answered Oct 18 '22 14:10

Samuel Neff