static - C# Hashtable of FileSystemWatchers -


i'm trying create hashtable of filesystem watchers. keep running record of active filesystemwatchers directories watching keys. via form user can add , delete folders watch, visible in listview or something.

my main problem how "keep" hash table between methods , classes. i'm bit of novice c# , doesn't seem work way i'm used in vb.net.

so have (stripped down simplify):

    public partial class mainform : form     {         public static hashtable globalhashtable;         public mainform()         {             initializecomponent();         }           public void button1click(object sender, eventargs e)         {             filesystemwatcher watcher1 = new filesystemwatcher(@"c:\");             globalhashtable.add(@"c:\",watcher1);         }     } } 

so filesystemwatcher added hashtable. since globalhashtable static (?) won't work. making non static means have create instance of when buttton pressed, have new 1 each time it's not "kept". problem how keep table in memory between methods , classes.

i'm sure i've majorly misunderstood i'm new of this. doubt half decent way this, if has better way, please go ahead!

thanks,

matt

expanding on @ron beyer's suggestion can this:

private dictionary<string, filesystemwatcher> _filesystemwatchermap;  public mainform() {     initializecomponent();      _filesystemwatchermap = new dictionary<string, filesystemwatcher>(); }  public void button1click(object sender, eventargs e) {     string pathtowatch = @"c:\"; // must different path each time otherwise throw     var watcher = new filesystemwatcher(pathtowatch);     _filesystemwatchermap.add(pathtowatch, watcher); } 

this way methods in mainform can access file watchers.

if need share among forms created mainform can pass data before showing dialog.

if other form created in different way can create static class this:

public static class filewatchermap {     private static dictionary<string, filesystemwatcher> _filesystemwatchermap = new dictionary<string,filesystemwatcher>();      public static void addwatcher(string path, filesystemwatcher fsw)     {         _filesystemwatchermap.add(path, fsw);     }      public static void removewatcher(string path)     {         _filesystemwatchermap.remove(path);     } } 

then in click handler add watcher list:

public void button1click(object sender, eventargs e) {     string pathtowatch = @"c:\"; // must different path each time otherwise throw     var watcher = new filesystemwatcher(pathtowatch);     filewatchermap.addwatcher(pathtowatch, watcher); } 

now filewatchermap class accessible other form


Comments