Ryan McDonnell - Pursuing Web Application Zen

FileSystemWatcher fires multiple times for the same event

Tuesday, September 7th, 2004 at 12:00 am

The FileSystemWatcher component recently gave me some headaches when firing events in response to changes to files it was watching.  In one case, when modifying a file, the FileSystemWatcher was firing four times for the same event… or so it seemed. After some research and testing, I came to the realization that four events were being fired. The FileSystemWatcher was doing it’s job right. I had simply disregarded the effects of anti-virus and native application file system handling. A simple change of a text file in Notepad may seem like only one file system event, but adding an anti-virus program’s checks into the mix can easily make that single event turn into four unique file system actions.

http://www.experts-exchange.com/Programming/Languages/.NET/Q_20708008.html

One Comment

  1. Jason Jakob

    easy fix just check the last modified time. if it’s the same then don’t do anything. it will go through the if the first time and subsequent fires will ignore:

    private DateTime fileLastModified = DateTime.Now.AddDays(-1);

    void watcher_Changed(object sender, FileSystemEventArgs e) {
    FileInfo fi = new FileInfo(e.FullPath);
    if (fi.LastWriteTime > fileLastModified) {
    fileLastModified = fi.LastWriteTime;
    ProcessFileChange(e.FullPath);
    }
    }

    private void ProcessFileChange(string filename) {
    //work your magic
    }

About Ryan McDonnell

I am a web application developer living in southern California. Commonly called a “jack of all trades” by collegues, I constantly strive to broaden my knowledge into other fields.
More about Ryan McDonnell »


 Subscribe in a reader

Quick Links & Notes

© 2004-2010 Ryan McDonnell. View my profile on LinkedIn
Some rights reserved under the Creative Commons Attribution-Share Alike 3.0 United States License.