如何计算多个位置的更改次数?

How to count number of changes on multiple locations?

我正在使用 FileSystemWatcher 监视网络存储上的多个文件夹。 问题是我必须计算每个位置的更改次数。计数器未正确递增,因为当更改第二个位置的文件时,计数器已设置为 2。

我有以下代码:

private void button1_Click(object sender, EventArgs e)
{
    FileMonitor(Directory.GetCurrentDirectory());
    FileMonitor(@"C:\Users\NET\Desktop");
}

static int _counter = 1;
public static int Counter
{
    get { 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;
    }
    finally
    {
        watcher.EnableRaisingEvents = true;
    }
}

如何为每个 FileMonitor 实例设置唯一的计数器?

问题在于您将 计数器设为静态,因此该计数器为所有监视器共享。 有一些方法可以帮助您:

  1. 您可以更改您的计数器,以获得计数器列表。然后你的第一个监视器使用计数器[0]等等。
  2. 您可以创建一个 class 具有两个属性的监视器和计数器,每次您进入 OnChanged 时,您都可以增加此监视器的计数器。

希望对您有所帮助

编辑:
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;
            }
            finally
            {
                Watcher.EnableRaisingEvents = true;
            }
        }
    }