Search code examples
c#filesystemwatcher

FileSystemWatcher calls handler three times


I have written a test app to try out the FileSystemWatcher example code from msdn.

It basically works but the handler gets called three times. Does any one know why?

namespace FileWatcherTest
{
    public partial class Form1 : Form
    {
        private FileSystemWatcher watcher;
        public Form1()
        {
            InitializeComponent();
            string testPath = 
                Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) 
                + @"\Test";
            InitialiseFileWatcher(testPath, "example.txt");
        }

        private void InitialiseFileWatcher(string path, string fileName)
        {
            watcher = new FileSystemWatcher();
            watcher.Path = path;
            watcher.NotifyFilter = NotifyFilters.LastWrite;
            watcher.Filter = fileName;
            watcher.Changed += new FileSystemEventHandler(OnFarmListChanged);
            // Begin watching.
            watcher.EnableRaisingEvents = true;
        }

        private static void OnFarmListChanged(object source, FileSystemEventArgs e)
        {
            string text = "File: " + e.FullPath + " " + e.ChangeType;
            MessageBox.Show(text);
        }
    }
}

Solution

  • As part of the documentation in the link you included:

    Common file system operations might raise more than one event. For example, when a file is moved from one directory to another, several OnChanged and some OnCreated and OnDeleted events might be raised. Moving a file is a complex operation that consists of multiple simple operations, therefore raising multiple events. Likewise, some applications (for example, antivirus software) might cause additional file system events that are detected by FileSystemWatcher.