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?
I came up with the following DirectoryInfo extension method which wraps the native DirectoryInfo.Delete() method and attempts to "safely delete" the specified folder:
This method requires the following COM reference: Microsoft Internet Controls x
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.
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.
Some more info here:
How to monitor process' IO activity using C#?
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.