views:

48

answers:

1

I am using FileSystemWatcher to monitor a folder, and it seems to be preventing the folder's parent from being deleted.

For example, I have the file structure:

C:\Root\FolderToWatch\...

with the FileSystemWatcher targeting FolderToWatch. While my program is running, if I go to Windows Explorer and try to delete Root, I get an error "Cannot delete Root: access is denied".

However, if I delete FolderToWatch FIRST, I can then delete Root without incident.

Here's some code if you want to play with it:

static void Main(string[] args) {

    var watcher = new FileSystemWatcher(@"C:\Root\FolderToWatch");

    watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
       | NotifyFilters.FileName | NotifyFilters.DirectoryName;

    watcher.Changed += (sender, e) => Console.WriteLine(e.FullPath);
    watcher.Created += (sender, e) => Console.WriteLine(e.FullPath);
    watcher.Deleted += (sender, e) => Console.WriteLine(e.FullPath);
    watcher.Renamed += (sender, e) => Console.WriteLine(e.FullPath);

    watcher.EnableRaisingEvents = true;

    Console.WriteLine("Press \'q\' to quit.");
    while (Console.Read() != 'q');
}

Questions:

  • Why does the FileSystemWatcher hang onto it's target's parent like that?
  • How can I stop this behavior? I would like the user to be able to freely move or delete directories in Windows Explorer.
+1  A: 

Hi,

It is because by deleting the root folder you would also be implicitly deleting any folders it contains, namley in your example "FolderToWatch" which would be owned by the FileSystemWatcher process.

Enjoy!

Doug
But if that's the reason, why is it OK to delete `FolderToWatch` directly?
Henry Jackson