FileSystemWatcher 可以监控到文件某路径下是否有新的文件产生,并且可以获取到最新文件的基本信息。
一、单条路径监控
main(){
string pathArray = @"D:\Program Files (x86)\Microsoft Office";
FileSystemWatcher watch = new FileSystemWatcher(); // 实例化FileSystemWatcher对象
watch.Path = pathArray; //监控的路径
watch.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName |
NotifyFilters.DirectoryName;
watch.Filter = "*"; // 监控的新生成的文件格式
watch.IncludeSubdirectories = true; // 监控子目录
watch.Created += new FileSystemEventHandler(OnChangFile); // 有文件创建则触发事件(watch.Created)
watch.EnableRaisingEvents = true; // 启动监控
}
private void OnChangFile(object sender, FileSystemEventArgs e)
{
Console.WriteLine("有新文件产生!");
Console.WriteLine(e.FullPath); // 打印文件的路径
Console.WriteLine(e.Name); // 打印文件的名称
}
二、多路条径监控
main(){
string path1 = "D:\Program Files (x86)\Microsoft Office"; // 监控路径1
string path2 = "D:\Program Files (x86)\Microsoft Visual Studio 14.0\lib"; // 监控路径2
string[] pathArray = { path1, path2};
for (int i = 0; i < pathArray.Count(); i++)
{
FileSystemWatcher watch = new FileSystemWatcher();
watch.Path = pathArray[i];
watch.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName |
NotifyFilters.DirectoryName;
watch.Filter = "*";
watch.IncludeSubdirectories = true; // 监控子目录
watch.Created += new FileSystemEventHandler(OnChangFile);
watch.EnableRaisingEvents = true;
}
private void OnChangFile(object sender, FileSystemEventArgs e)
{
Console.WriteLine("有新文件产生!");
Console.WriteLine(e.FullPath); // 打印文件的路径
Console.WriteLine(e.Name); // 打印文件的名称
}
}
博客主要还是为了巩固自己,如对他人有帮助,实在是我的荣幸!