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

c#FileSystemWatcher在侦听OnChanged时触发两次,c#,filesystemwatcher,C#,Filesystemwatcher,试图实现FileSystemWatcher,但保存文件时会调用OnChanged函数两次。根据其他一些帖子,我怀疑LastWrite过滤器有多个事件?我原以为NotifyFilters会将其限制为仅在写入文件时触发,但其他原因会导致函数运行两次e.ChangeType只告诉我文件已更改,但不确切地告诉我如何更改。有没有办法将此限制为只运行一次 public MainWindow() { InitializeComponent(); FileSys

试图实现
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(), "");
    }
}

你可以自己过滤掉它,正如我发布的那样。

弗雷德里克答案的另一种选择:

我想到的一个小的解决方法是,如果OnChanged方法已经在执行,那么可以防止它执行

例如:

private bool IsExecuting { get; set; }

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

        // rest of your code

        IsExecuting = false;
    }
}

我想你的URL搞乱了你只是太快了:)完美修复。谢谢这是我不久前使用的方法,效果很好。这不起作用,仍然采用这种方法。正确答案