问题
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