views:

88

answers:

2

Consider this code:

string dir = Environment.CurrentDirectory + @"\a";
Directory.CreateDirectory(dir);
FileSystemWatcher watcher = new FileSystemWatcher(dir);
watcher.IncludeSubdirectories = false;
watcher.EnableRaisingEvents = true;
Console.WriteLine("Deleting " + dir);
Directory.Delete(dir, true);
if (Directory.Exists(dir))
{
    Console.WriteLine("Getting dirs of " + dir);
    Directory.GetDirectories(dir);
}
Console.ReadLine();

Interestingly this throws an UnauthorizedAccessException on Directory.GetDirectories(dir).

Deleting the watched directory returns without error, but Directory.Exists() still returns true and the directory is still listed. Furthermore accessing the directory yields "Access denied" for any program. Once the .NET application with the FileSystemWatcher exits the directory vanishes.

How can I watch a directory while still allowing it to be properly deleted?

+2  A: 

You did in fact delete the directory. But the directory won't be physically removed from the file system until the last handle that references it is closed. Any attempt to open it in between (like you did with GetDirectories) will fail with an access denied error.

The same mechanism exists for files. Review FileShare.Delete

Hans Passant
+1  A: 

Try this line:

 if (new DirectoryInfo(dir).Exists)

instead of:

if (Directory.Exists(dir))
MTs