I have very weird behavior. I have,
Directory.Delete(tempFolder, true);
if (Directory.Exists(tempFolder))
{
}
Sometimes Directory.Exists return true. Why? May be the explorer is open?
The rm command removes complete directories, including subdirectories and files. The rmdir command removes empty directories.
So, all you really have to do is call WipeFile and supply the full path of the file to be deleted, as well as the number of times you want to overwrite it.
To delete the specified directory and all its subdirectories, use the Directory. Delete() method.
The directory is the application's current working directory. The directory specified by path is not empty. The directory is read-only or contains a read-only file. The directory is being used by another process.
The directory specified by path is read-only, or recursive is false and path is not an empty directory. The directory is the application's current working directory. The directory contains a read-only file.
The directory is the application's current working directory. The directory contains a read-only file. The directory is being used by another process. The caller does not have the required permission.
The DeleteFile function marks a file for deletion on close. Therefore, the file deletion does not occur until the last handle to the file is closed. Subsequent calls to CreateFile to open the file fail with ERROR_ACCESS_DENIED." The RemoveDirectory function marks a directory for deletion on close.
Directory.Delete
calls the Windows API function RemoveDirectory
. The observed behavior is documented:
The
RemoveDirectory
function marks a directory for deletion on close. Therefore, the directory is not removed until the last handle to the directory is closed.
The .NET documentation is unfortunately missing this information. Whether the static Directory.Delete
method opens a handle to the directory is not documented. Likewise, if it does, it is not documented when the handle is closed.
Without any of this information, the best you can do is to poll for completion:
Directory.Delete(tempFolder, true);
while (Directory.Exists(tempFolder)) Thread.Sleep(0);
// At this point the directory has been removed from the filesystem
Even though polling should generally be avoided in preference of events, installing a filesystem watcher would be a bit over the top for this. Still, keep in mind, that this operation does not come for free, particularly when dealing with a network drive.
This information, however, does not help in finding a better solution than the one described above (polling for completion).
GC.Collect()
does not run finalizers. This, too, appears to work by buying extra time.
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