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?
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.
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.
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.
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.
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#?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With