Modified event of FileSystemWatcher getting triggered multiple times [duplicate]

江枫思渺然 提交于 2019-12-23 05:32:08

问题


I want to monitor the following

  • New File being created/copied to the directory
  • Existing file edited

I use the following code to subscribe to the created and changed event of the FileSystemWatcher class.I have noted some issues with FSW Class.

  • On replacing files, the changed event is getting triggered numerous times.

How can i get over this issue.Kindly advice.

 watcher.Path = watchpath;
 watcher.Filter = "*.*";
 watcher.Created += new FileSystemEventHandler(copied);
 watcher.Changed += new FileSystemEventHandler(Watcher_Changed);
 watcher.NotifyFilter = NotifyFilters.LastWrite;
 watcher.EnableRaisingEvents = true;

For a single item copied to the folder,the following events are raised

  *******> Created 
    -----> Changed 
    -----> Changed 

回答1:


Yes, that is expected as already mentioned in the comments. Also have a look at : FileSystemWatcher Changed event is raised twice

to have a workaround you will need to add a dictionary which will track the raised events for every files.

Dictionary<string, DateTime> lastWriteDate //fileName - Last write date time

and in changed event you will have to handle it like below,

    private static void Watcher_Changed(object sender, System.IO.FileSystemEventArgs e)
    {
        string filePath = e.FullPath;
        DateTime writeDate = System.IO.File.GetLastWriteTime(filePath);
        if (lastWriteDate.ContainsKey(filePath))
        {
            if (lastWriteDate[filePath] == writeDate) 
                //Exit as we already have raised an event for this
                return;
            lastWriteDate[filePath] = writeDate;
        }
        else
        {
            lastWriteDate.Add(filePath, writeDate);
        }

        //Do your stuff.
    }


来源:https://stackoverflow.com/questions/55015132/modified-event-of-filesystemwatcher-getting-triggered-multiple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!