【发布时间】:2018-01-12 05:29:28
【问题描述】:
我有一个我正在做的宠物项目,FileSystemWatcher 让我很烦恼。
这是初始化代码:
for (var xx = 0; xx < _roots.Count; xx++)
{
var watcher = new FileSystemWatcher();
var root = _roots[xx];
watcher.Path = root;
// watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName;
watcher.Filter = "*.*";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
watcher.EnableRaisingEvents = true;
_rootWatchers.Add(watcher);
}
假设我们正在观看的根目录“c:\root”,并且有一个子目录“c:\root\subdir”,其中包含一个名为“file1.txt”的文件。
监视程序已启动并正在运行,我删除了“file1.txt”。当调用处理程序并检查 FileSystemEventArgs 的值时。
我期待e.Name == "file1.txt" 和e.FullPath == "c:\\root\\subdir\\file1.txt。
实际值为"subdir" 和"c:\\root\\subdir"。
我确定这是我在某个地方的文档中遗漏的一些简单的东西。
【问题讨论】:
-
我认为这可能会有所帮助:stackoverflow.com/questions/11255360/…
-
这是我在提出问题之前在 FileSystemWatcher 上阅读的第一个问题。它没有帮助,因为它涵盖了使用
Name和FullName的实例属性来获取信息。这个问题是关于返回目录信息而不是文件信息的事件。 -
如果我现在靠近键盘,我会尝试一个想法:设置一个测试,只对一个路径进行删除监控。如果文件详细信息符合预期,请添加其余的复杂性以查看代码示例中的其他任何内容是否导致问题。我看到的每篇关于文件观察器的文章都表明应该报告文件路径(我认为是相对路径)。也许您将多个事件处理程序映射到同一个方法会使您的水浑浊。只是一个猜测。我会进行一些测试,但我在手机自动取款机上
标签: c# .net filesystemwatcher