Search code examples
c#asp.netwinformsfilesystemwatcher

File System Watcher OnChanged and OnCreated event gets called multiple times for a single file.


Here is my code:

m_Watcher.Filter = "*.*";
                    m_Watcher.Path = settings.FolderName;
                    m_Watcher.IncludeSubdirectories = true;
                    m_Watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
                    m_Watcher.Changed += new FileSystemEventHandler(OnChanged);
                    m_Watcher.Created += new FileSystemEventHandler(OnCreated);
                    //m_Watcher.Deleted += new FileSystemEventHandler(OnChanged);
                    m_Watcher.Renamed += new RenamedEventHandler(OnRenamed);
                    m_Watcher.EnableRaisingEvents = true;

Whenever I am copying a file or a folder to the folder being watched the OnCreated and OnChanged method gets fired multiple times. Can anyone tell me where I have gone wrong ?


Solution

  • In your event handlers, check the ChangeType property of the event raised. There are a number of different change types and several can be called, depending on what's happened in the file system.

    https://msdn.microsoft.com/en-us/library/t6xf43e0%28v=vs.110%29.aspx

    You may only wish to handle certain change types. So, it's just a matter of ensuring that there's logic in there to only handle the required change types you wish to manage. You may not need to handle so many of the events you've specified so far.