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.
mostly for future me :)
I wrote a wrapper using Rx:
Usage:
I had to combine several ideas from the posts above and add file locking check to get it working for me:
Any duplicated
OnChanged
events from theFileSystemWatcher
can be detected and discarded by checking theFile.GetLastWriteTime
timestamp on the file in question. Like so:Sorry for the grave dig, but I've been battling this issue for a while now and finally came up with a way to handle these multiple fired events. I would like to thank everyone in this thread as I have used it in many references when battling this issue.
Here is my complete code. It uses a dictionary to track the date and time of the last write of the file. It compares that value, and if it is the same, it suppresses the events. It then sets the value after starting the new thread.
I have changed the way I monitor files in directories. Instead of using the FileSystemWatcher I poll locations on another thread and then look at the LastWriteTime of the file.
Using this information and keeping an index of a file path and it's latest write time I can determine files that have changed or that have been created in a particular location. This removes me from the oddities of the FileSystemWatcher. The main downside is that you need a data structure to store the LastWriteTime and the reference to the file, but it is reliable and easy to implement.
I was able to do this by added a function that checks for duplicates in an buffer array.
Then perform the action after the array has not been modified for X time using a timer: - Reset timer every time something is written to the buffer - Perform action on tick
This also catches another duplication type. If you modify a file inside a folder, the folder also throws a Change event.