Multiple Configurable FileSystemWatcher methods

2020-08-02 02:59发布

问题:

In the past I have created Windows Services which monitor one directory where the path is configurable by referencing a config file like this:

fileSystemWatcher1.Path = ConfigurationManager.AppSettings["WatchPath1"];

I've also watched multiple configurable paths by defining multiple fileSystemWatcher methods.

        fileSystemWatcher1.Path = ConfigurationManager.AppSettings["WatchPath1"];
        fileSystemWatcher2.Path = ConfigurationManager.AppSettings["WatchPath2"];
        fileSystemWatcher3.Path = ConfigurationManager.AppSettings["WatchPath3"];

The above works if I know before hand how many folders I am likely going to monitor so my question is, what approach can I take to make this dynamic when I don't know how many folders need to be monitored? What I'd like to do is continue to use a config or XML file and for each entry create FileSystemWatcher with the path specified in the file.

I would also need to be able to dynamically create the a method for each FileSystemWatcher so specific actions can be taken when a file system event is triggered.

Example code to created dynamically:

private void fileSystemWatcher1_Created(object sender,  System.IO.FileSystemEventArgs e)
            {
                Library.WriteErrorLog("New file detected in watch folder.  File: " + e.FullPath);
                // Do stuff with file
            }

Is this possible? If so how could I go about achieving this?

回答1:

Store a list of FileSystemWatcher object, which you initialise when you start the class.

List<FileSystemWatcher> fsWatchers = new List<FileSystemWatcher>();

To add a new watcher...

public void AddWatcher(String wPath) {
    FileSystemWatcher fsw = new FileSystemWatcher();
    fsw.Path = wPath;
    fsw.Created += file_OnCreated;
    fsw.Changed += file_OnChanged;
    fsw.Deleted += file_OnDeleted;
    fsWatchers.Add(fsw);
}

private void file_OnDeleted(object sender, FileSystemEventArgs e) {

}

private void file_OnChanged(object sender, FileSystemEventArgs e) {

}

private void file_OnCreated(object sender, FileSystemEventArgs e) {

}

In each of the event handlers, cast sender to a FileSystemWatcher if you need to interact directly with it. To get the full path, use the get methods on the event args object (e).

You could potentially simplify it a little by having a single event handler assigned to all the events on the FileSystemWatcher.

private void file_OnFileEvent(object sender, FileSystemEventArgs e) {
    String path = e.FullPath;
    if (e.ChangeType == WatcherChangeTypes.Changed) {

    } else if (e.ChangeType == WatcherChangeTypes.Created) {

    }
}


标签: c#