【发布时间】:2016-04-01 17:05:09
【问题描述】:
我的程序需要监控多个位置,但为每个位置触发相同的代码。由于单个FileSystemWatcher 无法监控多个位置,但是否可以创建多个实例并为每个实例传递文件夹路径?
我无法对每个 FileSystemWatcher 进行硬编码,因为需要及时添加越来越多的位置,而这需要由最终用户完成,因为我必须手动硬编码每次都是新的FileSystemWatcher。所以我的计划是将文件夹路径保存到一个文件中,程序只为列表中的每个路径创建一个FileSystemWatcher。但我不知道这是否有可能。
在这里尝试使用工厂方法模式建议: 我收到错误消息:“'List' 不包含 'add' 的定义
public void StartWatchers()
{
string[] ArrayPaths = new string[2];
List<FileSystemWatcher> watchers = new List<FileSystemWatcher>();
ArrayPaths[0] = @"K:\Daily Record Checker\Test\Test1";
ArrayPaths[1] = @"K:\Daily Record Checker\Test\Test2";
int i = 0;
foreach (String String in ArrayPaths)
{
watcher.add(MyWatcherFatory(ArrayPaths[i]));
i++;
}
//Do other stuff....
//....
//Start my watchers...
foreach (FileSystemWatcher watcher in watchers)
{
Watcher.EnableRaisingEvents = true;
i++;
}
}
FileSystemWatcher MyWatcherFatory(string path)
{
FileSystemWatcher watcher = new FileSystemWatcher(path);
watcher.Changed += Watcher_Created;
watcher.Path = path;
watcher.Filter = "*.csv";
return watcher;
}
private void Watcher_Created(object sender, FileSystemEventArgs e)
{
System.Threading.Thread.Sleep(1000);
FileInfo fileInfo = new FileInfo(e.FullPath);
if (!IsFileLocked(fileInfo))
{
CheckNumberOfRecordsInFile(e.FullPath);
}
}
【问题讨论】:
-
您更新的代码有“Watcher.add”...您想添加到您的列表中:watchers.Add
-
我正在编写 Owlsolo 的代码,但将其更改为 hte list 仍会导致“'List
'不包含'add'的定义 -
我看到您已经接受了下面的答案,但请注意,我没有说要使用“添加”,而是说“添加”:“watchers.Add”。大写在 C# 中很重要。
标签: c# instance filesystemwatcher