My FileSystemWatcher class was raising multiple events when hooked into the Changed and Created events for monitoring files today.
I found out why! To debug and trigger these events I was using one of my favourite text editors, EditPlus which performed a save of my file in multiple segments, consequently raising these events more than once!
Check out the following quote below for more information on this:
Multiple Created Events Generated for a Single Action
You may notice in certain situations that a single creation event generates multiple Created events that are handled by your component. For example, if you use a FileSystemWatcher component to monitor the creation of new files in a directory, and then test it by using Notepad to create a file, you may see two Created events generated even though only a single file was created. This is because Notepad performs multiple file system actions during the writing process. Notepad writes to the disk in batches that create the content of the file and then the file attributes. Other applications may perform in the same manner. Because FileSystemWatcher monitors the operating system activities, all events that these applications fire will be picked up.
Note: Notepad may also cause other interesting event generations. For example, if you use the ChangeEventFilter to specify that you want to watch only for attribute changes, and then you write to a file in the directory you are watching using Notepad, you will raise an event . This is because Notepad updates the Archived attribute for the file during this operation.
So watch out, this could also be the case when Anti Virus decides to intervene too.
5 Comments
How odd. I experienced the exact same thing today with a file watcher I was testing. I use UltraEdit, and I was getting 3 events when I expected one. Sounds like the same problem. How timely
Totally weird.
It’s amazing what happens around you at the same time in the world.
Is there any work around this problem. I am watching a directory and if some body copied a excel file to it, I am loading that data to DB. Multiple event generation is screwing up the whole thing….
Could you pl explain how to avoid this multiple events ?
try
{
if (e.ChangeType==WatcherChangeTypes.Changed)
{
using (StreamWriter sw = new StreamWriter(@”C:\WINDOWS\Temp\log.txt”, true))
{
string message = “File ” + e.FullPath + ” Has been ” + e.ChangeType + ” on ” + System.DateTime.Now;
sw.WriteLine(message);
watcher.EnableRaisingEvents = false;
}
}
}
hope this would help you guys to solve the issue
Post a Comment