Search code examples
c#windowstriggersconsole-applicationfilesystemwatcher

FileSystemWatcher events called multiple times


I have created a Console application to watch a specific folder by using filesystemwatcher. when i make any changes or create or rename or delete in any of the file it will trigger a event. but when i change the file 2 events are getting triggered.I need only one event should be triggered for that respective action....

Below are my code which triggering 2 events when i change the file

public static void FileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
        {
            FileSystemWatcher watcher = new FileSystemWatcher();
            string time = DateTime.Now.ToString("dd-MM-yyyy hh:mm:ss");

                string myFilePath = e.FullPath;
                string ext = Path.GetExtension(myFilePath);
                if (ext == ".tmp" || ext == ".TMP" || ext == "")
                {

                }
                else
                {
                    string date = DateTime.Now.ToString("dd-MM-yyyy hh:mm:ss");
                    Console.ForegroundColor = ConsoleColor.Blue;
                    Console.WriteLine("A new file has been changed - " + e.Name + " " + "on" + " " + date + " File Changed", Console.ForegroundColor);
                    //  SendAttachmentMail("A File Has Been Changed - " + e.Name + "", date, "File Changed");
                    //File_Date = date;
                    //watcher.Dispose();



            }
        } 

Solution

  • This behavior is documented. What is also documented is that you are not guaranteed that all events will be delivered. Application must protect itself against either case.

    Common file system operations might raise more than one event. For example, when a file is moved from one directory to another, several OnChanged and some OnCreated and OnDeleted events might be raised. Moving a file is a complex operation that consists of multiple simple operations, therefore raising multiple events. Likewise, some applications (for example, antivirus software) might cause additional file system events that are detected by FileSystemWatcher.

    Also note that the above is Win32 behavior, FSW is just wrapping up the operating system feature into a nicer interface.