Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. FileSystemWatcher Events Fired Twice

FileSystemWatcher Events Fired Twice

Scheduled Pinned Locked Moved C#
help
9 Posts 5 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • realJSOPR Offline
    realJSOPR Offline
    realJSOP
    wrote on last edited by
    #1

    Given the following code:

    FileSystemWatcher m_watcher = new FileSystemWatcher();

    private void MyMethod()
    {
    m_watcher.BeginInit();
    m_watcher.Filter = "*myfile*.*";
    m_watcher.IncludeSubdirectories = false;
    m_watcher.Path = "C:\\MyEwatchedFolder";
    m_watcher.NotifyFilter = NotifyFilters.LastWrite;
    m_watcher.Changed += new FileSystemEventHandler(watcher_Changed);
    m_watcher.EndInit();

    m\_watcher.EnableRaisingEvents = true;
    

    }

    void watcher_Changed(object sender, FileSystemEventArgs e)
    {
    FileSystemWatcher watcher = sender as FileSystemWatcher;
    if (e.ChangeType == WatcherChangeTypes.Changed)
    {
    MessageBox.Show(string.Format("File!\n\n{0}", e.FullPath));
    }
    }

    The Changed handler is getting called twice. I've looked all over googkle and can't find a reason or a way to fix it.

    "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
    -----
    "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

    D L N J 4 Replies Last reply
    0
    • realJSOPR realJSOP

      Given the following code:

      FileSystemWatcher m_watcher = new FileSystemWatcher();

      private void MyMethod()
      {
      m_watcher.BeginInit();
      m_watcher.Filter = "*myfile*.*";
      m_watcher.IncludeSubdirectories = false;
      m_watcher.Path = "C:\\MyEwatchedFolder";
      m_watcher.NotifyFilter = NotifyFilters.LastWrite;
      m_watcher.Changed += new FileSystemEventHandler(watcher_Changed);
      m_watcher.EndInit();

      m\_watcher.EnableRaisingEvents = true;
      

      }

      void watcher_Changed(object sender, FileSystemEventArgs e)
      {
      FileSystemWatcher watcher = sender as FileSystemWatcher;
      if (e.ChangeType == WatcherChangeTypes.Changed)
      {
      MessageBox.Show(string.Format("File!\n\n{0}", e.FullPath));
      }
      }

      The Changed handler is getting called twice. I've looked all over googkle and can't find a reason or a way to fix it.

      "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
      -----
      "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

      D Offline
      D Offline
      Dave Kreskowiak
      wrote on last edited by
      #2

      Have to tried increasing the FSW's InternalBufferSize?? It must be a multiple of the O/S page size(?? I think!). Default is 8KB. Keep in mind that each event that is internally queued needs 16 + (2 * filename length) bytes to store, so if you're encountering long filenames, you could overflow the buffer and not know anything about it.

      A guide to posting questions on CodeProject[^]
      Dave Kreskowiak Microsoft MVP Visual Developer - Visual Basic
           2006, 2007, 2008

      realJSOPR 1 Reply Last reply
      0
      • realJSOPR realJSOP

        Given the following code:

        FileSystemWatcher m_watcher = new FileSystemWatcher();

        private void MyMethod()
        {
        m_watcher.BeginInit();
        m_watcher.Filter = "*myfile*.*";
        m_watcher.IncludeSubdirectories = false;
        m_watcher.Path = "C:\\MyEwatchedFolder";
        m_watcher.NotifyFilter = NotifyFilters.LastWrite;
        m_watcher.Changed += new FileSystemEventHandler(watcher_Changed);
        m_watcher.EndInit();

        m\_watcher.EnableRaisingEvents = true;
        

        }

        void watcher_Changed(object sender, FileSystemEventArgs e)
        {
        FileSystemWatcher watcher = sender as FileSystemWatcher;
        if (e.ChangeType == WatcherChangeTypes.Changed)
        {
        MessageBox.Show(string.Format("File!\n\n{0}", e.FullPath));
        }
        }

        The Changed handler is getting called twice. I've looked all over googkle and can't find a reason or a way to fix it.

        "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
        -----
        "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

        L Offline
        L Offline
        Luc Pattyn
        wrote on last edited by
        #3

        AFAIK FileSystemWatcher makes only a best attempt at signaling file system actions; it does not guarantee to report everything, and I expect it to report more actions per file than you care to receive, e.g. writing a file changes the content (once or more) and changes the metadata (such as last write time); the file system itself only guarantees metadata once the file got closed, but AFAIK may or may not update things in between. So you really have to defend yourself against multiple reports. :)

        Luc Pattyn [Forum Guidelines] [My Articles]


        Love, happiness and fewer bugs for 2009!


        realJSOPR 1 Reply Last reply
        0
        • L Luc Pattyn

          AFAIK FileSystemWatcher makes only a best attempt at signaling file system actions; it does not guarantee to report everything, and I expect it to report more actions per file than you care to receive, e.g. writing a file changes the content (once or more) and changes the metadata (such as last write time); the file system itself only guarantees metadata once the file got closed, but AFAIK may or may not update things in between. So you really have to defend yourself against multiple reports. :)

          Luc Pattyn [Forum Guidelines] [My Articles]


          Love, happiness and fewer bugs for 2009!


          realJSOPR Offline
          realJSOPR Offline
          realJSOP
          wrote on last edited by
          #4

          I set up a list of recently "handled" filenames, and if the name is in the list, I don't do anything. If it's not in the list I add it. If the list grows beyond a certain threshold, I delete the first item in the list. It's a kludge but it appears to work fine since I'm not expecting more than a couple of files at a time.

          "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
          -----
          "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

          L 1 Reply Last reply
          0
          • D Dave Kreskowiak

            Have to tried increasing the FSW's InternalBufferSize?? It must be a multiple of the O/S page size(?? I think!). Default is 8KB. Keep in mind that each event that is internally queued needs 16 + (2 * filename length) bytes to store, so if you're encountering long filenames, you could overflow the buffer and not know anything about it.

            A guide to posting questions on CodeProject[^]
            Dave Kreskowiak Microsoft MVP Visual Developer - Visual Basic
                 2006, 2007, 2008

            realJSOPR Offline
            realJSOPR Offline
            realJSOP
            wrote on last edited by
            #5

            The file names are approximately 30 characters long, but I'm only throwing one at a time at the application as a test, so I don't think the buffer would be filling up, even at the default 8k size.

            "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
            -----
            "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

            D 1 Reply Last reply
            0
            • realJSOPR realJSOP

              I set up a list of recently "handled" filenames, and if the name is in the list, I don't do anything. If it's not in the list I add it. If the list grows beyond a certain threshold, I delete the first item in the list. It's a kludge but it appears to work fine since I'm not expecting more than a couple of files at a time.

              "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
              -----
              "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

              L Offline
              L Offline
              Luc Pattyn
              wrote on last edited by
              #6

              OK FWIW you could turn it into an MRU list by: first removing the new item, if that fails and list filled to capacity removeAt(0); then always add the new item. :)

              Luc Pattyn [Forum Guidelines] [My Articles]


              Love, happiness and fewer bugs for 2009!


              1 Reply Last reply
              0
              • realJSOPR realJSOP

                Given the following code:

                FileSystemWatcher m_watcher = new FileSystemWatcher();

                private void MyMethod()
                {
                m_watcher.BeginInit();
                m_watcher.Filter = "*myfile*.*";
                m_watcher.IncludeSubdirectories = false;
                m_watcher.Path = "C:\\MyEwatchedFolder";
                m_watcher.NotifyFilter = NotifyFilters.LastWrite;
                m_watcher.Changed += new FileSystemEventHandler(watcher_Changed);
                m_watcher.EndInit();

                m\_watcher.EnableRaisingEvents = true;
                

                }

                void watcher_Changed(object sender, FileSystemEventArgs e)
                {
                FileSystemWatcher watcher = sender as FileSystemWatcher;
                if (e.ChangeType == WatcherChangeTypes.Changed)
                {
                MessageBox.Show(string.Format("File!\n\n{0}", e.FullPath));
                }
                }

                The Changed handler is getting called twice. I've looked all over googkle and can't find a reason or a way to fix it.

                "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                -----
                "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

                N Offline
                N Offline
                Not Active
                wrote on last edited by
                #7

                I've run into this also with the change event. As I recall it is accurate because file systems generates multiple actions when a file is changed. I was able to get around it with this bit of clugyness void Watcher_Changed(object sender, FileSystemEventArgs e) { // Disable events so we don't recieve multiple events Watcher.EnableRaisingEvents = false; Watcher.Changed -= new FileSystemEventHandler(Watcher_Changed); // Do some work... // Now reset so we get the next event Watcher.Changed += new FileSystemEventHandler(Watcher_Changed); Watcher.EnableRaisingEvents = true; }


                only two letters away from being an asset

                1 Reply Last reply
                0
                • realJSOPR realJSOP

                  The file names are approximately 30 characters long, but I'm only throwing one at a time at the application as a test, so I don't think the buffer would be filling up, even at the default 8k size.

                  "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                  -----
                  "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

                  D Offline
                  D Offline
                  Dave Kreskowiak
                  wrote on last edited by
                  #8

                  Ehh, it was a thought...

                  A guide to posting questions on CodeProject[^]
                  Dave Kreskowiak Microsoft MVP Visual Developer - Visual Basic
                       2006, 2007, 2008

                  1 Reply Last reply
                  0
                  • realJSOPR realJSOP

                    Given the following code:

                    FileSystemWatcher m_watcher = new FileSystemWatcher();

                    private void MyMethod()
                    {
                    m_watcher.BeginInit();
                    m_watcher.Filter = "*myfile*.*";
                    m_watcher.IncludeSubdirectories = false;
                    m_watcher.Path = "C:\\MyEwatchedFolder";
                    m_watcher.NotifyFilter = NotifyFilters.LastWrite;
                    m_watcher.Changed += new FileSystemEventHandler(watcher_Changed);
                    m_watcher.EndInit();

                    m\_watcher.EnableRaisingEvents = true;
                    

                    }

                    void watcher_Changed(object sender, FileSystemEventArgs e)
                    {
                    FileSystemWatcher watcher = sender as FileSystemWatcher;
                    if (e.ChangeType == WatcherChangeTypes.Changed)
                    {
                    MessageBox.Show(string.Format("File!\n\n{0}", e.FullPath));
                    }
                    }

                    The Changed handler is getting called twice. I've looked all over googkle and can't find a reason or a way to fix it.

                    "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                    -----
                    "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

                    J Offline
                    J Offline
                    Jason C Bourne
                    wrote on last edited by
                    #9

                    Hello, This is normal, what you see as one logical operation actually involves two different physical operations that throw this event. I've learnt that a few years ago, I just can't remember what were the physical operations exactly but it made sense. Something already occurs when the file gets opened or when the write operation is not yet flushed, but the fact is that you can actually detect that. A the first event, the file size is not yet correct: in the case of a new file, the size will be zero, and for modifications... well you have to know the previous size ;-) Below is a sample of something I wrote a few years ago, please forgive me I wrote it in VB and I am not particularly proud of this piece of code ;-) Here, I had the advantage that I was monitoring one file, so I kept remembering its size. I remember there is a more elegant solution in the source code of Log4Net, the popular open source logging framework. They use a file system watcher to watch their own config file for changes. If I remember well, they make use of timer or something like that, the technique works always and you always get only 1 event. Sorry it is late for me, but you should look at this source code, it contains your answer :) JC Private _ChangeWatcher As FileSystemWatcher Private Sub InitWatcher() _ChangeWatcher = New System.IO.FileSystemWatcher() AddHandler _ChangeWatcher.Changed, AddressOf Watcher_Changed With _ChangeWatcher .BeginInit() .EnableRaisingEvents = True .IncludeSubdirectories = False .NotifyFilter = IO.NotifyFilters.LastWrite .Path = _FolderToMonitor .Filter = _FileName .EndInit() End With End Sub ''' ----------------------------------------------------------------------------- ''' <summary> ''' Called when the FileSystemWatcher detects a change (matching ''' the NotifyFilter) on the specified file. In this case, the handler ''' will be called when a file is created or updated. ''' </summary> ''' <remarks> ''' We cannot rely on the ChangeType, it is always CHANGED, ''' even when the file was created. Luckily, it has no impact. ''' </remarks> ''' ----------------------------------------------------------------------------- Private Sub Watcher_Changed(ByVal sender As Object, ByVal e As System.IO.FileSystemEventArgs) SyncLock Me If String.Compare(e.Name, _

                    1 Reply Last reply
                    0
                    Reply
                    • Reply as topic
                    Log in to reply
                    • Oldest to Newest
                    • Newest to Oldest
                    • Most Votes


                    • Login

                    • Don't have an account? Register

                    • Login or register to search.
                    • First post
                      Last post
                    0
                    • Categories
                    • Recent
                    • Tags
                    • Popular
                    • World
                    • Users
                    • Groups