Search code examples
c#filesystemwatcher

c# FileSystemWatcher triggers twice when listening to OnChanged


Trying to implement FileSystemWatcher but the OnChanged function is called twice when the file is saved. based on some other posts, I suspect the LastWrite filter has multiple events? I thought the NotifyFilters would limit it to only firing when the file is written to, but something else is causing the function to run twice. e.ChangeType only tells me the file changed, but not exactly how. Is there a way to limit this to running only once?

    public MainWindow()
    {
        InitializeComponent();

        FileSystemWatcher fsw = new FileSystemWatcher(path);
        fsw.NotifyFilter = NotifyFilters.LastWrite;
        fsw.EnableRaisingEvents = true;
        fsw.Changed += new FileSystemEventHandler(OnChanged);
    }

    private void OnChanged(object sender, FileSystemEventArgs e)
    {
        if (newString == null)
        {
            using (StreamReader sr = new StreamReader(new FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
            {
                lastString = sr.ReadToEnd();
            }
            difference = lastString;
        } else {
            using (StreamReader sr = new StreamReader(new FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
            {
                newString = sr.ReadToEnd();
            }
            int newCount = newString.Count();
            int count = lastString.Count();
            // MessageBox.Show("last:" + lastString.Count().ToString(), "next: " + newString.Count());
            difference = newString.Remove(0,5);
            lastString = newString;
        }
        Application.Current.Dispatcher.Invoke(new Action(() => { tb_content.Text = difference; }));
        MessageBox.Show(e.ChangeType.ToString(), "");
    }
}

Solution

  • You can filter it out yourself, as I've posted here.