FileSystemWatcher Changed event is raised twice

前端 未结 30 3314
死守一世寂寞
死守一世寂寞 2020-11-22 06:01

I have an application where I am looking for a text file and if there are any changes made to the file I am using the OnChanged eventhandler to handle the event

30条回答
  •  旧时难觅i
    2020-11-22 06:10

    Any duplicated OnChanged events from the FileSystemWatcher can be detected and discarded by checking the File.GetLastWriteTime timestamp on the file in question. Like so:

    DateTime lastRead = DateTime.MinValue;
    
    void OnChanged(object source, FileSystemEventArgs a)
    {
        DateTime lastWriteTime = File.GetLastWriteTime(uri);
        if (lastWriteTime != lastRead)
        {
            doStuff();
            lastRead = lastWriteTime;
        }
        // else discard the (duplicated) OnChanged event
    }
    

提交回复
热议问题