Hank
Hank

Reputation: 8477

FileSystemWatcher keeping parent directory

I am using FileSystemWatcher to monitor a folder, and it seems to be preventing the folder's parent from being deleted, but doesn't prevent the folder itself 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');
}

Why does the FileSystemWatcher hang onto it's target's parent like that, but not the target itself?

Upvotes: 3

Views: 518

Answers (1)

Doug
Doug

Reputation: 5328

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!

Upvotes: 1

Related Questions