Search code examples
c#filesystemwatcher

FileSystemWatcher missing file changes from other program


Specific question. I've set up a program that watches for changes to a text file with numbers.

            FileSystemWatcher mikeWatcher = new FileSystemWatcher();
            System.IO.WaitForChangedResult postMike;
            string filePath = @"c:\path.txt";
            mikeWatcher.Path = Path.GetDirectoryName(filePath);
            mikeWatcher.Filter = Path.GetFileName(filePath);

            // Wait for change to the file
            postMike = mikeWatcher.WaitForChanged(System.IO.WatcherChangeTypes.Changed);

After this the code continues with the process once the WaitForChanged flag gets complete.

...

The issue I'm having is that while the flag is successfully triggered when I manually change the text file and hit save, when the other program (matlab) writes to and saves to that same file, the flag doesn't seem to be triggered.

I've confirmed that it is indeed the same file being changed (Path is correct) and that the change is registered in the "last modified date". Also, it does appear that the matlab process is closing the text file after saving so its not a release issue, I don't think.

Any thoughts or advice? It'd be easiest for me to change my c# code then the matlab code. All suggestions welcome!


Solution

  • The solution here is to stop using FileSystemWatcher, and instead use a timer to scan the directory for changes.

    I have tried to use FileSystemWatcher in two projects and in both cases I found it too unreliable. It would miss some events, delay some events, and report some events twice. I gave up, and haven't used it since.

    This answer may not be popular but I'm convinced that the only correct way to use FileSystemWatcher is in comments, like this:

    // Tried FileSystemWatcher, but it was far too unreliable.