Search code examples
c#filesystemwatcher

How to dispose of event listeners from FileSystemWatcher events


Using FileSystemWatcher, is there a way to dispose of instances of event listeners after an event has fired?

My program basically listens for the creation of a batch.complete.xml file in newly created folders. Once the program detects that the file has been created there is no need to continue listening in this folder.

My program looks like this:

public static void watchxmlfile(batchfolderpath){

 var deliverycompletewatcher = new FileSystemWatcher();    

 deliverycompletewatcher.Path = batchfolderpath;

 deliverycompletewatcher.Filter = "*.xml";

 deliverycompletewatcher.Created += new FileSystemEventHandler(OnChanged);

 deliverycompletewatcher.EnableRaisingEvents = true;

}


private static void OnChanged(object sender, FileSystemEventArgs e)
{
    BuildingestionXml(string.Format(@"{0}\{1}",e.FullPath,e.Name));
    Console.WriteLine(@"Second: Success sending{0}\{1}", e.FullPath, e.Name);
}

So when the above event is fired I no longer need to watch for events in "batchfolderpath" unless watchxmlfile() is explicitly called which will have a new path.

I am trying to prevent memory leaks from too many instances of listeners for the above event.


Solution

  • You don't need to assign a variable, sender is the FileSystemWatcher:

    private static void OnChanged(object sender, FileSystemEventArgs e)
    {
        BuildingestionXml(string.Format(@"{0}\{1}",e.FullPath,e.Name));
        Console.WriteLine(@"Second: Success sending{0}\{1}", e.FullPath, e.Name);
        ((FileSystemWatcher)sender).Dispose();
    }