开发者

FileSystemWatcher keeping parent directory

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?


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜