FileSystemWatcher 保留父目录

发布于 2024-09-04 04:04:11 字数 1213 浏览 3 评论 0原文

我正在使用 FileSystemWatcher 监视文件夹,它似乎阻止删除该文件夹的,但不会阻止该文件夹本身 > 免遭删除。

例如,我的文件结构为:

C:\Root\FolderToWatch\...

FileSystemWatcher 定位为 FolderToWatch。当我的程序运行时,如果我转到 Windows 资源管理器并尝试删除 Root,我会收到错误“无法删除 Root:访问被拒绝”。

但是,如果我首先删除 FolderToWatch,那么我就可以毫无意外地删除 Root

如果您想使用它,这里有一些代码:

static void Main(string[] args) {

    var watcher = new FileSystemWatcher(@"C:\Root\FolderToWatch");

    watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
       | NotifyFilters.FileName | NotifyFilters.DirectoryName;

    watcher.Changed += (sender, e) => Console.WriteLine(e.FullPath);
    watcher.Created += (sender, e) => Console.WriteLine(e.FullPath);
    watcher.Deleted += (sender, e) => Console.WriteLine(e.FullPath);
    watcher.Renamed += (sender, e) => Console.WriteLine(e.FullPath);

    watcher.EnableRaisingEvents = true;

    Console.WriteLine("Press \'q\' to quit.");
    while (Console.Read() != 'q');
}

为什么FileSystemWatcher会像这样挂在其目标的父级上,而不是目标本身?

I am using FileSystemWatcher to monitor a folder, and it seems to be preventing the folder's parent from being deleted, but doesn't prevent the folder itself from being deleted.

For example, I have the file structure:

C:\Root\FolderToWatch\...

with the FileSystemWatcher targeting FolderToWatch. While my program is running, if I go to Windows Explorer and try to delete Root, I get an error "Cannot delete Root: access is denied".

However, if I delete FolderToWatch FIRST, I can then delete Root without incident.

Here's some code if you want to play with it:

static void Main(string[] args) {

    var watcher = new FileSystemWatcher(@"C:\Root\FolderToWatch");

    watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
       | NotifyFilters.FileName | NotifyFilters.DirectoryName;

    watcher.Changed += (sender, e) => Console.WriteLine(e.FullPath);
    watcher.Created += (sender, e) => Console.WriteLine(e.FullPath);
    watcher.Deleted += (sender, e) => Console.WriteLine(e.FullPath);
    watcher.Renamed += (sender, e) => Console.WriteLine(e.FullPath);

    watcher.EnableRaisingEvents = true;

    Console.WriteLine("Press \'q\' to quit.");
    while (Console.Read() != 'q');
}

Why does the FileSystemWatcher hang onto it's target's parent like that, but not the target itself?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

雨巷深深 2024-09-11 04:04:11

这是因为通过删除根文件夹,您还将隐式删除它包含的任何文件夹,即您的示例“FolderToWatch”中的文件夹,该文件夹将由 FileSystemWatcher 进程拥有。

享受!

It is because by deleting the root folder you would also be implicitly deleting any folders it contains, namley in your example "FolderToWatch" which would be owned by the FileSystemWatcher process.

Enjoy!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文