Directory.Exists and FileSystemWatcher

703 views Asked by At

Why does Directory.Exists returns true for a directory observed by FileSystemWatcher even if it was deleted.

I must call EnableRaisingEvents = false before checking Directory.Exists since it always returns true.

Edit:

I am trying to check if folder was deleted or connection lost using error event. To add a delay i testedT it with a Tread.Sleep() command before checking directory, but it still thinks it exists.

2

There are 2 answers

0
Hans Passant On BEST ANSWER

You simply see the Honest Truth, the directory is not actually deleted. The operating system actively prevents the directory from disappearing when a process has a handle opened on it. Like FSW does when you start watching. Or when the directory is the Environment.CurrentDirectory of a process.

This doesn't otherwise prevent you from deleting the directory. Very similar to the FileShare.Delete option in .NET for files. It will now exist in limbo, waiting for the last handle to be closed before it can actually be removed from the file system. Any program that tries to use the directory while it is this limbo state will be slapped to ensure that this is eventually going to happen.

You must call the FileSystemWatcher.Dispose() method.

0
James On

FileSystemWatcher is known for raising events at the start of the event not when the event is completed. There's lots of question about it on here regarding waiting for copying to finish.

The same would apply to deleting a folder. It takes time for a folder to be deleted