繁体   English   中英

FileSystemWatcher触发没有文件名的事件

[英]FileSystemWatcher fires event without the file name

我有一个宠物项目,正在研究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"

我敢肯定,这是我在某个地方的文档中错过的简单事情。

您是正确的,您面临的问题实际上是忘记设置属性的问题之一。

如果设置watcher.IncludeSubdirectories = true; ,即使在更深的层次上,您也会收到有关文件删除的通知。

在默认模式下, FileSystemWatcher仅记录对给定目录的更改。 子目录被建模为类似于文件的目录条目,它们中的任何添加/删除都将直接报告为对子目录的更改(如果您在OnChanged处理程序中选中FileSystemEventArgs.ChangeType属性,将会看到)。

即使打开子目录监视,您仍然会收到subdir目录的更改事件( FileSystemEventArgs.ChangeType = WatcherChangeTypes.Changed ),因为在删除其中的文件时也会对其进行修改。 这是文件删除事件的补充。

我的测试代码:

static void Main(string[] args)
{
    var watcher = new FileSystemWatcher();

    watcher.Path = @"C:\test_dir";
    // 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.IncludeSubdirectories = true;

    watcher.EnableRaisingEvents = true;

    while (true)
    {
    }
}

private static void OnRenamed(object sender, RenamedEventArgs e)
{
    Console.WriteLine($"OnRenamed: {e.FullPath}, {e.OldFullPath}");
}

private static void OnChanged(object sender, FileSystemEventArgs e)
{
    Console.WriteLine($"OnChanged: {e.ChangeType}, {e.Name}[{e.FullPath}]");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM