c# - How to count number of changes on multiple locations? -


i'm using filesystemwatcher monitor multiple folders on network storage. problem have count number of changes each location. counter not correctly incremented because when file second location changed counter set 2.

i have following code:

private void button1_click(object sender, eventargs e) {     filemonitor(directory.getcurrentdirectory());     filemonitor(@"c:\users\net\desktop"); }  static int _counter = 1; public static int counter {     { return _counter; }     set { _counter = value; } }  private void filemonitor(string path) {     filesystemwatcher watcher = new filesystemwatcher();     watcher.path = path;     watcher.notifyfilter = notifyfilters.lastaccess | notifyfilters.lastwrite    | notifyfilters.filename | notifyfilters.directoryname;     watcher.filter = "*.csv";     watcher.changed += (s, e) => onchanged(e.fullpath, watcher);      watcher.enableraisingevents = true; }  private static void onchanged(string path, filesystemwatcher watcher) {     try     {         watcher.enableraisingevents = false;         messagebox.show(counter.tostring());         counter = counter + 1;     }         {         watcher.enableraisingevents = true;     } } 

how can set counter unique each filemonitor instance?

the problem make counter static, counter shared monitors. there ways can you:

  1. you can change counter, list of counters. first monitor uses counters[0] , on.
  2. you can create class 2 properties, monitor , counter, , every time enter in onchanged can increase counter of monitor.

i hope can you.

edit:
mainwindow.xaml.xs

 list<filemonitor> monitors = new list<filemonitor>();          public mainwindow()         {             initializecomponent();         }          private void button_click(object sender, routedeventargs e)         {           monitors.add(new filemonitor(@"c:"));           monitors.add(new filemonitor(@"d:"));         } 

filemonitor.cs

public class filemonitor     {         public int counter { get; set; }         public filesystemwatcher watcher { get; set; }         public filemonitor(string path)         {             counter = 0;             watcher = new filesystemwatcher();             watcher.path = path;             watcher.notifyfilter = notifyfilters.lastaccess | notifyfilters.lastwrite            | notifyfilters.filename | notifyfilters.directoryname;             watcher.filter = "*.csv";             watcher.changed += (s, e) => onchanged();              watcher.enableraisingevents = true;         }          private void onchanged()         {             try             {                 watcher.enableraisingevents = false;                 messagebox.show(counter.tostring());                 counter = counter + 1;             }                         {                 watcher.enableraisingevents = true;             }         }     }  

Comments