OnChanged 中的 streamReader 会触发两次?

streamReader inside OnChanged fires twice?

我有一个监视特定文件的小应用程序,每当它发生变化时,我的应用程序都应该在循环中执行操作,但是某些东西不止一次触发该功能!!这是我的代码

private void OnChanged(object source, FileSystemEventArgs e)
{
    if (e.FullPath == @"C:\test.txt")
    {
        string textFilePath = @"C:\test.txt";

        try
        {
            using (var streamReader = File.OpenText(textFilePath))
            {
                var lines = streamReader.ReadToEnd().Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                foreach (var line in lines)
                {
                    //actions here
                }
            }
        }
        catch (Exception)
        {
        }
    }
}

所以我猜测当 streamreader File.OpenText 以某种方式再次触发该功能时,我在循环中?!有什么想法吗?

来自MSDN

The Changed event is raised when changes are made to the size, system attributes, last write time, last access time, ...

是的,打开(实际上:关闭)文件将再次引发 Changed 事件。

您可以使用 NotifyFilter 来限制观察者触发的操作。

解决方案 所以我做了一件小事来控制这个问题,我添加了一个计数器并且总是检查它是否不是第一次,跳过并将它重新分配给 0.

private int fireCounter = 0;

    private void OnChanged(object source, FileSystemEventArgs e)
    {
        fireCounter++;

        if (fireCounter == 1)
        {
            delete();

            if (e.FullPath == @"C:\test.txt")
            {
                Thread.Sleep(2000);
                //I added Sleep for two seconds because without it sometimes it wont work

                string textFilePath = @"C:\test.txt";
                try
                {
                    using (var streamReader = File.OpenText(textFilePath))
                    {
                        var lines = streamReader.ReadToEnd().Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                        foreach (var line in lines)
                        {
                            //Actions Here
                        }
                    }
                }
                catch (Exception)
                {
                }
            }
        }
        else
        {
            fireCounter = 0;
        }
    }