locked
Duplicate Events with FileSystemWatcher RRS feed

  • Question

  • HI,

    I am developing a user control  which needs to check file on  every operation.For this i am using FileSystemWacther.
    I need to initialize FileSystemWacther events in 2 places.
    1)in EndInit();
    2)in a Property FileNameChange

    NotifyFilters:  NotifyFilters.LastWrite | NotifyFilters.FileName |NotifyFilters.DirectoryName

    now its producing duplicate events with FileSystemWacther. 


    how to avoid this please help me , thanks in advance.

     My sample coed:

    public Class MyWatcher : System.ComponentModel.Component,ISupportInitialize
    {
     private System.ComponentModel.Container components = null;

    FileSystemWatcher watcher = new FileSystemWatcher();
    private void ReleaseEvents()
            {
                if (watcher != null)
                {
                    watcher.Renamed -= new RenamedEventHandler(fileRenamed);
                    watcher.Deleted -= new FileSystemEventHandler(fileDeleted);
                    watcher.Changed -= new FileSystemEventHandler(fileChanged);
                    watcher.Created -= new FileSystemEventHandler(fileCreated);
                }
            }
            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            // private bool disposed = false;

            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    if (watcher != null)
                    {
                        ReleaseEvents();
                        watcher.Dispose();
                    }
                    if (components != null)
                    {
                        components.Dispose();
                    }
                  

                }
               
                base.Dispose(disposing);

            }
            #region ISupportInitialize Members

            public void BeginInit()
            {

            }
            public void EndInit()
            {
                    this.fullpath ="some Path";
                     FileWatcher();
            }

            string fullpath = null;
            string FullPath
            {
                get { return fullpath; }
                set { fullpath = value; FileWatcher();}//

            }
            public void FileWatcher()
            {


              
                if (fullpath != null)
                {
                    watcher.Path = Path.GetDirectoryName(fullpath);
                    watcher.Filter = fileName;
                   
                    watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName |NotifyFilters.DirectoryName ;
                    
                    ReleaseEvents();

                    watcher.Renamed += new RenamedEventHandler(fileRenamed);
                    watcher.Deleted += new FileSystemEventHandler(fileDeleted);
                    watcher.Changed += new FileSystemEventHandler(fileChanged);               
                    watcher.Created += new FileSystemEventHandler(fileCreated);
                   

                    watcher.EnableRaisingEvents = true;

                }

            }
           
            void fileChanged(object sender, FileSystemEventArgs e)
            {
               
                     ReadMethod(e.FullPath);

              
            }
            
            void fileCreated(object sender, FileSystemEventArgs e)
            {


                ReadMethod(e.FullPath);


            }
            void fileDeleted(object sender, FileSystemEventArgs e)
            {
             
            }
            void fileRenamed(object sender, RenamedEventArgs e)
            {
                ReadMethod(e.FullPath);

            }
            private void ReadMethod(string path)
            {
                    //reading some text File
            }
    }
    • Edited by ManasMSDN Tuesday, October 6, 2009 2:49 PM code
    Monday, October 5, 2009 11:24 PM

All replies

  • Hi,

    how does image control updates image changes .
    ex. i have an image on winform  and if i update image with another image then it should display new image .
    but how does this works?
    is there anyhting to do with FileWatcher in order to check image size,location,creation time?
    please help me!
    thanks in advance.
    • Changed type ManasMSDN Thursday, October 1, 2009 3:16 PM text
    • Merged by Aland Li Thursday, October 8, 2009 5:36 AM Duplicated.
    Thursday, October 1, 2009 3:10 PM
  • Hi,

    how does image control updates image changes .
    ex. i have an image on winform  and if i update image with another image then it should display new image .
    but how does this works?
    is there anyhting to do with FileWatcher in order to check image size,location,creation time?
    please help me!
    thanks in advance.
    • Edited by ManasMSDN Thursday, October 1, 2009 3:31 PM text
    • Moved by CoolDadTx Friday, October 2, 2009 1:55 PM WinForms related (From:.NET Base Class Library)
    • Merged by Aland Li Wednesday, October 7, 2009 2:56 AM The same topic
    Thursday, October 1, 2009 3:18 PM
  • Not really sure what you're asking.

    Have you tried to Invalidate or Refresh the control?
    Mick Doherty
    http://dotnetrix.co.uk
    Thursday, October 1, 2009 5:46 PM
  • The FileSystemWatcher provides you with the ability to monitor the file system for changes. The NotifyFilters enumeration lists the different types of changes you can monitor. If you set the FileSystemWatcher's Path property to the location of your image, you will be able to detect changes including size, file name, folder name and creation time. Note that I don't believe you will be able to detect all types of location changes unless you monitor the entire file system.
    Friday, October 2, 2009 12:35 PM
  • Hi,

    You could always take a peek and disassemble the System.Drawing.dll using Reflector (http://www.red-gate.com/products/reflector/) and see how it hangs together. 

    Andez
    Andez (Please mark as answer if it helps)
    Friday, October 2, 2009 12:51 PM
  • Hi,

    i figured it , the problem was with FileSystemWatcher . It causes events to raise multiple times .

    I am developing a custom component.
    i have to call FileSystemWatcher  twice  based on condition

    1) from proeprty
    2) from method
    how to unregister the FileSystemWatcher  events ? and where ?


    Friday, October 2, 2009 9:11 PM
  • You'll need to show your code that's initializing this, as well as the declaration of your watcher.

    My guess , given what you are describing, is that you're not reusing the same watcher, or your not unsubscribing before changing your subscription.

    Make sure to unsubscribe when you change based on your events, for example, if you have:

    public class WatcherComponent
    {
       private FileSystemWatcher watcher;
    
       public WatcherComponent()
       {
           // Initialize one time, sharing instances!
           this.watcher = new FileSystemWatcher();
           this.watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName |NotifyFilters.DirectoryName ;
           this.watcher.Path = myPath;
           
       }
    
       private string filename;
       public string Filename
       {
           get { return this.filename; }
           set
           {
               if (value != this.filename) {
                    this.filename = value;
                    // Call a single function to reinitialize!
                    ResetWatcher();
               }
           }
        }
    
        protected override void OnInit(EventArgs e)
        {
            // Initialize values, then startup watcher...
            this.filename = "default_file.txt";
            this.ResetWatcher(); 
        }
    
       private void ResetWatcher()
       {
           // If the watcher is active, unsubscribe from it...
           if (watcher.EnableRaisingEvents)
           {
              watcher.EnableRaisingEvents = false;
              watcher.Changed -= OnChanged;
              watcher.Created -= OnChanged;
              watcher.Deleted -= OnChanged;
              watcher.Renamed -= OnRenamed;
           }
    
           watcher.Filter = this.Filename; // Set file to watch...
           watcher.Changed += OnChanged;
           watcher.Created += OnChanged;
           watcher.Deleted += OnChanged;
           watcher.Renamed += OnRenamed;
    
           watcher.EnableRaisingEvents = true;
       }
    }
    The code above isn't perfect, but the basic idea should suffice.

    Reed Copsey, Jr. - http://reedcopsey.com
    Monday, October 5, 2009 11:52 PM
  • Hi, thanks for your explanation,

    here is my code.


    public Class MyWatcher : System.ComponentModel.Component,ISupportInitialize
    {
     private System.ComponentModel.Container components = null;

    FileSystemWatcher watcher = new FileSystemWatcher();
    private void ReleaseEvents()
            {
                if (watcher != null)
                {
                    watcher.Renamed -= new RenamedEventHandler(fileRenamed);
                    watcher.Deleted -= new FileSystemEventHandler(fileDeleted);
                    watcher.Changed -= new FileSystemEventHandler(fileChanged);
                    watcher.Created -= new FileSystemEventHandler(fileCreated);
                }
            }
            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            // private bool disposed = false;

            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    if (watcher != null)
                    {
                        ReleaseEvents();
                        watcher.Dispose();
                    }
                    if (components != null)
                    {
                        components.Dispose();
                    }
                  

                }
               
                base.Dispose(disposing);

            }
            #region ISupportInitialize Members

            public void BeginInit()
            {

            }
            public void EndInit()
            {
                    this.fullpath ="some Path";
                     FileWatcher();
            }

            string fullpath = null;
            string FullPath
            {
                get { return fullpath; }
                set { fullpath = value; FileWatcher();}//

            }
            public void FileWatcher()
            {


              
                if (fullpath != null)
                {
                    watcher.Path = Path.GetDirectoryName(fullpath);
                    watcher.Filter = fileName;
                   
                    watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName |NotifyFilters.DirectoryName ;
                    
                    ReleaseEvents();

                    watcher.Renamed += new RenamedEventHandler(fileRenamed);
                    watcher.Deleted += new FileSystemEventHandler(fileDeleted);
                    watcher.Changed += new FileSystemEventHandler(fileChanged);               
                    watcher.Created += new FileSystemEventHandler(fileCreated);
                   

                    watcher.EnableRaisingEvents = true;

                }

            }
           
            void fileChanged(object sender, FileSystemEventArgs e)
            {
               
                     ReadMethod(e.FullPath);

              
            }
            
            void fileCreated(object sender, FileSystemEventArgs e)
            {


                ReadMethod(e.FullPath);


            }
            void fileDeleted(object sender, FileSystemEventArgs e)
            {
             
            }
            void fileRenamed(object sender, RenamedEventArgs e)
            {
                ReadMethod(e.FullPath);

            }
            private void ReadMethod(string path)
            {
                    //reading some text File
            }
    }
    Tuesday, October 6, 2009 12:16 AM
  • Hi!

    please check my code , help me with this problem..............................


    thanks in advance.
    Tuesday, October 6, 2009 3:25 AM
  • Hi!

    please check my code , help me with this problem..............................


    thanks in advance.
    Tuesday, October 6, 2009 2:59 PM
  • Your code (that's posted, which obviously isn't the full code) looks reasonable.  Are you sure you're not creating more than instance of this watcher in your program?


    Reed Copsey, Jr. - http://reedcopsey.com
    Tuesday, October 6, 2009 3:48 PM
  • Hi,

    the above code is the full code except ReadMethod()--which reads text file with
     ArrayList alist= null; ---instance variable

    void ReadMethod()
    {

     using (FileStream fs=new FileStream(filename,FileMode.Open,FileAccess.ReadWrite,FileShare.ReadWrite))
                {
                    System.IO.StreamReader reader = new System.IO.StreamReader(fs);
                 if (alist== null)
                {
                    alist= new ArrayList();
                }
                else
                {
                    alist.Clear();
                }
                   alist.Add(reader);

                    reader.Close();
                    reader.Dispose();

                    fs.Close();
                    fs.Dispose();
                }
     
    }
    Tuesday, October 6, 2009 4:01 PM
  • Where are you using this?  Do you possibly have more than one instance?

    Reed Copsey, Jr. - http://reedcopsey.com
    Tuesday, October 6, 2009 4:39 PM
  • this is a component and i have couple of this kind of components placed on winform and am using this while drawing .
    so when ever file changes i need to redraw all components .
    Tuesday, October 6, 2009 4:42 PM
  • You're probably getting duplicate events because you have "couple of this kind of components placed on winform".

    Make sure that each component is watching a different file or directory, and not the same one.  Also, you may not need to track EVERY file event - (ie: renamed + changed + ..).  Try putting a Console.WriteLine in each event handler, and print out the filename property.  This should help you determine which component is firing, and help you elimnate the duplicates.
    Reed Copsey, Jr. - http://reedcopsey.com
    Tuesday, October 6, 2009 5:07 PM
  • Hi,
    i need to have each component must watch same file  and some other components some other files.
    Actually i am trying to develop  some user control kind of  behavior.

    Like when you drag and drop user control for multiple times and all these control objects points one user control file only on winform.So when ever you do some changes to user control, all user control objects on winform will gets the same effect.

    with this same concept i am trying to draw component.
    Tuesday, October 6, 2009 5:27 PM
  • Hi ManasMSDN,

    Could you please provide a code snippet?

    You can set the EnableRaisingEvents property of the FileSystemWatcher to false to stop firing events. You can get details and a sample about FileSystemWatcher from:
    http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx

    Regards,
    Aland Li


    Please mark the replies as answers if they help and unmark if they don't. This can be beneficial to other community members reading the thread.
    Wednesday, October 7, 2009 3:55 AM
  • hi.

    checck my another thread for what i am talking

    Duplicate Events with FileSystemWatcher

    Wednesday, October 7, 2009 4:19 AM
  • Hi,

    "Make sure that each component is watching a different file or directory, and not the same one"

    My Component objects which are placed on winform must watch 'same file' (It is just like an image file).
    So when ever image attributes changes i need to show them in all objects of that component.


    please help me!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! :-(
    Wednesday, October 7, 2009 9:37 PM