c#FileSystemWatcher在收听OnChanged时触发两次

时间:2018-01-11 18:37:27

标签: c# filesystemwatcher

尝试实现FileSystemWatcher但保存文件时会调用OnChanged函数两次。基于其他一些帖子,我怀疑LastWrite过滤器有多个事件?我认为NotifyFilters会将它限制为仅在写入文件时触发,但是其他东西导致函数运行两次。 e.ChangeType只告诉我文件已更改,但不确切如何更改。有没有办法将此限制为仅运行一次?

    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(), "");
    }
}

2 个答案:

答案 0 :(得分:2)

您可以自行过滤,因为我已发布here

答案 1 :(得分:1)

Frederik答案的另一种选择:

我想到的一个小解决方法是阻止OnChanged方法在执行时执行。

例如:

private bool IsExecuting { get; set; }

private void OnChanged(object sender, FileSystemEventArgs e)
{
    if (!IsExecuting) 
    {
        IsExecuting = true;

        // rest of your code

        IsExecuting = false;
    }
}