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 am afraid that this is a well-known bug/feature of the
FileSystemWatcher
class. This is from the documentation of the class:Now this bit of text is about the
Created
event, but the same thing applies to other file events as well. In some applications you might be able to get around this by using theNotifyFilter
property, but my experience is says that sometimes you have to do some manual duplicate filtering (hacks) as well.A while ago I bookedmarked a page with a few FileSystemWatcher tips. You might want to check it out.
I have a very quick and simple workaround here, it does work for me, and no matter the event would be triggered once or twice or more times occasionally, check it out:
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.
Event if not asked, it is a shame there are no ready solution samples for F#. To fix this here is my recipe, just because I can and F# is a wonderful .NET language.
Duplicated events are filtered out using
FSharp.Control.Reactive
package, which is just a F# wrapper for reactive extensions. All that can be targeted to full framework ornetstandard2.0
:You could try to open it for write, and if successful then you could assume the other application is done with the file.
Just opening it for write appears not to raise the changed event. So it should be safe.