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've "fixed" that problem using the following strategy in my delegate:
Here is my solution which helped me to stop the event being raised twice:
Here I have set the
NotifyFilter
property with only Filename and size.watcher
is my object of FileSystemWatcher. Hope this will help.Alot of these answers are shocking, really. Heres some code from my XanderUI Control library that fixes this.
My scenario is that I have a virtual machine with a Linux server in it. I am developing files on the Windows host. When I change something in a folder on the host I want all the changes to be uploaded, synced onto the virtual server via Ftp. This is how I do eliminate the duplicate change event when I write to a file ( which flags the folder containing the file to be modified as well ) :
Mainly I create a hashtable to store file write time information. Then if the hashtable has the filepath that is modified and it's time value is the same as the currently notified file's change then I know it is the duplicate of the event and ignore it.
Try with this code:
Here is a new solution you can try. Works well for me. In the event handler for the changed event programmatically remove the handler from the designer output a message if desired then programmatically add the handler back. example: