Search code examples
c#filepathfile-watcher

Avoid multiple FileSystemWatcher


I am currently working on a custom explorer that allows the user to define multiple root directories. To capture all changes in the system, I use a FileSystemWatcher for all specified root directories.

Now, of course, it can happen that the user defines two root directories that contain the same paths. For example, C:\Windows and C:\Windows\System32\en-US

Then, when a file in these paths is modified (e.g. C:\Windows\System32\en-US\Licenses), the corresponding event handler is executed twice.

So is there a way to compare FileSystemWatchers using the observed paths and exclude all duplicates?

I already thought about assigning a single FileSystemWatcher to all paths and accordingly not watching the subpaths. But I assume that this is not quite as performant.

FYI:

foreach (string rootPath in Settings.RootPaths)
{
    FileSystemWatcher watcher = new FileSystemWatcher(rootPath);

    watcher.SynchronizingObject = this.treeView;
    watcher.NotifyFilter = NotifyFilters.Attributes
                            | NotifyFilters.CreationTime
                            | NotifyFilters.DirectoryName
                            | NotifyFilters.FileName
                            | NotifyFilters.LastAccess
                            | NotifyFilters.LastWrite
                            | NotifyFilters.Security
                            | NotifyFilters.Size;
    watcher.IncludeSubdirectories = true;
    watcher.EnableRaisingEvents = true;

    watcher.Created += ElementCreatedEventHandler;
    watcher.Deleted += ElementDeletedEventHandler;
    watcher.Renamed += ElementRenamedEventHandler;
}

Thanks in advance.


Solution

  • You have to check if rootpath1 is a subdir of another rootpath2, in that case you only need FileSystemWatcher on rootpath2.

    To check is subdir you can look at

    How to check if directory 1 is a subdirectory of dir2 and vice versa