[英]Filesystem Watcher - Multiple folders
I want to use filesystemwatcher to monitor multiple folders as follows. 我想使用filesystemwatcher监视多个文件夹,如下所示。 My below code only watches one folder: 我的下面的代码只看一个文件夹:
public static void Run()
{
string[] args = System.Environment.GetCommandLineArgs();
if (args.Length < 2)
{
Console.WriteLine("Usage: Watcher.exe PATH [...] [PATH]");
return;
}
List<string> list = new List<string>();
for (int i = 1; i < args.Length; i++)
{
list.Add(args[i]);
}
foreach (string my_path in list)
{
WatchFile(my_path);
}
Console.WriteLine("Press \'q\' to quit the sample.");
while (Console.Read() != 'q') ;
}
private static void WatchFile(string watch_folder)
{
watcher.Path = watch_folder;
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Filter = "*.xml";
watcher.Changed += new FileSystemEventHandler(convert);
watcher.EnableRaisingEvents = true;
}
But the above code monitors one folder and has not effect on the other folder. 但上面的代码监视一个文件夹,但对另一个文件夹没有影响。 What is the reason for that ? 这是什么原因?
A single FileSystemWatcher
can only monitor a single folder. 单个FileSystemWatcher
只能监视单个文件夹。 You will need to have multiple FileSystemWatchers
in order to implement this. 您需要具有多个 FileSystemWatchers
才能实现此目的。
private static void WatchFile(string watch_folder)
{
// Create a new watcher for every folder you want to monitor.
FileSystemWatcher fsw = new FileSystemWatcher(watch_folder, "*.xml");
fsw.NotifyFilter = NotifyFilters.LastWrite;
fsw.Changed += new FileSystemEventHandler(convert);
fsw.EnableRaisingEvents = true;
}
Note that if you want to modify these watchers later, you may want to maintain a reference to each created FileSystemWatcher
by adding it to a list or something. 请注意,如果您想稍后修改这些观察者,您可能希望通过将其添加到列表或其他内容来维护对每个创建的FileSystemWatcher
的引用。
EnableRaisingEvents
is default false
, you can try to put it before the Changed amd make a new watcher for each folder: EnableRaisingEvents
默认为false
,您可以尝试在Changed amd为每个文件夹创建一个新的观察器之前放置它:
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = watch_folder;
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Filter = "*.xml";
watcher.EnableRaisingEvents = true;
watcher.Changed += new FileSystemEventHandler(convert);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.