FileSystemWatcher 保留父目录
我正在使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是因为通过删除根文件夹,您还将隐式删除它包含的任何文件夹,即您的示例“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!