FileSystemWatcher Changed event is raised twice

前端 未结 30 3787
死守一世寂寞
死守一世寂寞 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条回答
  •  眼角桃花
    2020-11-22 06:21

    I know this is an old issue, but had the same problem and none of the above solution really did the trick for the problem I was facing. I have created a dictionary which maps the file name with the LastWriteTime. So if the file is not in the dictionary will go ahead with the process other wise check to see when was the last modified time and if is different from what it is in the dictionary run the code.

        Dictionary dateTimeDictionary = new Dictionary(); 
    
            private void OnChanged(object source, FileSystemEventArgs e)
                {
                    if (!dateTimeDictionary.ContainsKey(e.FullPath) || (dateTimeDictionary.ContainsKey(e.FullPath) && System.IO.File.GetLastWriteTime(e.FullPath) != dateTimeDictionary[e.FullPath]))
                    {
                        dateTimeDictionary[e.FullPath] = System.IO.File.GetLastWriteTime(e.FullPath);
    
                        //your code here
                    }
                }
    

提交回复
热议问题