使用FileSystemWatcher监视文件系统
我使用FileSystemWatcher
来监视文件系统。它可以观看特定的文件夹或驱动器。使用FileSystemWatcher监视文件系统
但我希望它在整个文件系统上意味着它应该在所有驱动器上观看。
对此有何想法?
我这么做。
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;
}
的一种方法是,以枚举所有的目录,并通过对他们每个人的使用FileSystemWatcher
看着他们。
但它会消耗大量的资源。因此,您可以对此链接进行替代查看:Filewatcher for the whole computer (alternative?)
你的意思是所有的'root'文件夹或所有文件夹和子文件夹(递归)? – 2013-04-10 11:07:05
“很多资源”我假设你的意思是“OutOfMemoryException”.. – 2013-04-10 11:07:17
您可以使用IncludeSubdirectories查看整个系统到逻辑驱动器。 试试这个代码,
string[] drives = Environment.GetLogicalDrives();
foreach(string drive in drives)
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = drive;
watcher.IncludeSubdirectories = true;
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.Filter = "*.txt";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
watcher.EnableRaisingEvents = true;
}
展示你的工作.. – 2013-04-10 11:04:02