C#文件监控 内部类使用
//实现文件 监视(监控)
public static class fileWatcher {
private static FileSystemWatcher? watcher;
public static bool EnableWathcer(DirectoryInfo directoryInfo)
{
try{
watcher = new FileSystemWatcher();
//添加要监控的文件夹
watcher.Path= directoryInfo.FullName;
//需要监听的内容 ,比如当lastWrite改变时触发的就会监听到
watcher.NotifyFilter = NotifyFilters.LastAccess
| NotifyFilters.LastWrite | NotifyFilters.FileName ;
//筛选需要监听的文件类型,这里只监听.cs 后缀的文件
watcher.Filter = "*.cs";
//当文件夹发生变化时触发
watcher.Changed+=new FileSystemEventHandler(OnChanged);
watcher.Renamed+=new RenamedEventHandler(OnChanged);
watcher.Deleted+=new FileSystemEventHandler(OnChanged);
//启动!
watcher.EnableRaisingEvents = true;
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
throw new Exception("文件监视器初始化失败",ex);
}
return true;
}
private static void OnChanged(object sender, FileSystemEventArgs e)
{
Console.WriteLine("文件发生了变化");
Console.WriteLine($"name:{e.Name}");//文件名
Console.WriteLine($"changeType:{e.ChangeType}");
Console.WriteLine($"fullPath:{e.FullPath}");
}
}
主函数调用:
var isSuccess=fileWatcher.EnableWathcer(
new DirectoryInfo(@"C:\Users\Administrator\Desktop\VScodeTest\FileSysTest"));
Console.WriteLine(isSuccess);
await Task.Delay(60000);
可以看到在指定文件夹下创建(修改)文件和重命名文件触发了事件
输出结果:
/ 文件发生了变化
// name:abc.cs
// changeType:Changed
// fullPath:C:\Users\Administrator\Desktop\VScodeTest\FileSysTest\abc.cs
// 文件发生了变化
// name:abc.cs
// changeType:Changed
// fullPath:C:\Users\Administrator\Desktop\VScodeTest\FileSysTest\abc.cs
// tostring:System.IO.FileSystemEventArgs
// 文件发生了变化
// name:aaa.cs
// changeType:Renamed
// fullPath:C:\Users\Administrator\Desktop\VScodeTest\FileSysTest\aaa.cs
// 文件发生了变化
// name:aaa.cs
// changeType:Changed
// fullPath:C:\Users\Administrator\Desktop\VScodeTest\FileSysTest\aaa.cs
最后要注意的一点是,在文件移动是时候可能会多次触发时间,
应为一个文件的移动可能要经过 新文件的创建、把原文件的内容复制到新文件、删除原文件等步骤,所以可能导致事件多次触发。
浙公网安备 33010602011771号