我的程序需要监控多个位置,但每个位置都会触发相同的代码。由于单个FileSystemWatcher
无法监控多个位置,但是是否可以为其创建多个实例并为每个位置传递一个文件夹路径?
我无法对每个FileSystemWatcher
进行硬编码,因为需要及时添加越来越多的位置,这需要由最终用户完成,因为对我来说这是非常不切实际的。每次手动硬编码新的FileSystemWatcher
。所以我的计划是将文件夹路径保存到文件中,程序只为列表中的每个路径创建一个FileSystemWatcher
。但我不知道这是否有可能是最轻微的。
在此处进行工厂方法模式建议尝试: 我收到了错误:"'列表'不包含'添加'
的定义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);
}
}
答案 0 :(得分:6)
FileSystemWatcher MyWatcherFatory(string path, object additionalParameters)
{
FileSystemWatcher watcher = new FileSystemWatcher(path);
watcher.Changed += myWatcherChangedMethod;//Attach them to the same listeners,,,
//Set additional parameters...
return watcher.
}
编辑:根据您提供的信息:
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 watcherin 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);
}
}