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. I am using the NotifyFilters.LastWriteTime
but still the event is getting fired twice. Here is the code.
public void Initialize()
{
FileSystemWatcher _fileWatcher = new FileSystemWatcher();
_fileWatcher.Path = "C:\\Folder";
_fileWatcher.NotifyFilter = NotifyFilters.LastWrite;
_fileWatcher.Filter = "Version.txt";
_fileWatcher.Changed += new FileSystemEventHandler(OnChanged);
_fileWatcher.EnableRaisingEvents = true;
}
private void OnChanged(object source, FileSystemEventArgs e)
{
.......
}
In my case the OnChanged
is called twice, when I change the text file version.txt
and save it.
I spent some significant amount of time using the FileSystemWatcher, and some of the approaches here will not work. I really liked the disabling events approach, but unfortunately, it doesn't work if there is >1 file being dropped, second file will be missed most if not all times. So I use the following approach:
This code worked for me.
I simple add a dupe check as follows:
I have created a Git repo with a class that extends
FileSystemWatcher
to trigger the events only when copy is done. It discards all the changed events exept the last and it raise it only when the file become available for read.Download FileSystemSafeWatcher and add it to your project.
Then use it as a normal
FileSystemWatcher
and monitor when the events are triggered.The main reason was first event's last access time was current time(file write or changed time). then second event was file's original last access time. I solve under code.
if you register to the OnChanged event, then by deleting the monitored file before changing it might work, as long as you only need to monitor the OnChange event..