Search code examples
c#iofilesystemwatcher

C#: Using FileSystemWatcher to watch for changes to files


Ok, so I learnt from How to check if a open file has been updated that I should use a FileSystemWatcher to watch for changes to files. Then now, the question is if I must keep track of many files, do I create 1 watcher for each file? Also, I must somehow dispose of the watcher once the file is closed. Is having a Dictionary<string, FileSystemWatcher> storing the filepath and the FileSystemWatcher the way to go? as I open more files, I add more watcher and as I close, dispose of the watchers appropriately. Will having too many watchers be a bad thing?

UPDATE

I just did

protected void AttachFileMonitor(EditorTabViewModel tab)
{
    string file = tab.FilePath;
    if (!_fsWatchers.ContainsKey(file))
    {
        var watcher = new FileSystemWatcher();
        watcher.Path = Path.GetDirectoryName(file);
        watcher.Filter = Path.GetFileName(file);
        watcher.Changed += (s, e) =>
        {
            string message = "";
            string caption = "";
            MessageBoxButton buttons = MessageBoxButton.YesNo;
            MessageBoxImage image = MessageBoxImage.Question;
            MessageBoxResult defaultResult = MessageBoxResult.Yes;
            MessageBoxResult result = _dialogSvc.GetMessageBox(message, caption, buttons, image, defaultResult);
            if (result == MessageBoxResult.Yes)
            {
                tab.Open(file);
            }
        };
        _fsWatchers.Add(file, watcher);
    }
}
protected void DetachFileMonitor(EditorTabViewModel tab)
{
    if (_fsWatchers.ContainsKey(tab.FilePath)) {
        _fsWatchers.Remove(tab.FilePath);
    }
}

I found that Changed() never gets triggered ...


Solution

  • It's enough if you create a watcher for each directory (and optionally, you can have the watcher to monitor a whole directory tree.) You can then use the events to compare the changed files with the list of files you are interested in.

    I would suggest you make some kind of "nanny" class for the watchers to ensure you doesn't dispose active watchers, or create duplicate. Just a tip :)

    Btw, yes, there's a limit, you can't create infinite watchers. In specific scenarios that can be a problem, but most likely, that's not the case for you