Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 932
Hank Avatar asked Dec 04 '25 15:12

Hank


1 Answers

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!

like image 192
Doug Avatar answered Dec 07 '25 04:12

Doug