简体   繁体   English

文件系统监视程序-文件夹已删除

[英]File System Watcher - Folder Deleted

I´m writing on an service to watch for the existence different files in diffent folders... I´m using filesystemwatchers to get the events. 我正在写一项服务来监视不同文件夹中存在的不同文件...我正在使用filesystemwatchers来获取事件。

As a part of the deployment one of the watched folders is deleted and new created from time to time. 作为部署的一部分,有时会删除其中一个监视的文件夹并新建一个。

As a result the service throws an error and is stopped... 结果,服务抛出错误并被停止...

Is it possible to catch that kind of error and recreate the filewatcher on the new folder by the service? 是否有可能捕获到这种错误并通过服务在新文件夹上重新创建Filewatcher?

Catch the deleted event, and then reschedule with timed poll to watch a new one? 赶上已删除的事件,然后重新安排定时轮询以观看新事件?

I don't have a compiler to hand right now but I knocked up this pseudo code: 我现在没有手拿的编译器,但我敲了这个伪代码:

using System;
using System.IO;


    public class Watcher : IDisposable{

    void Dispose(){ watcher.OnDeleted -= onDelete; }


    string file;
    FileSystemWatcher watcher; 
    FileSystemEventHandler onDelete;

        public class Watch(string file, FileSystemEventHandler onDelete) {
        this.file = file;   
        watcher = new FileSystemWatcher{ Path = file }
        this.OnDelete = onDelete;
        watcher.Deleted += onDelete;
        watcher.NotifyFilter = ...; // looking for delete event;
            // Begin watching.
            watcher.EnableRaisingEvents = true;
    }
    }


    public static class watch {

    Watcher watcher;

       public static void Main() {



        watcher = new Watcher("somedir", ondeleted);
        SetUpChangeWatchers();
        while(true){
            // stuff!

        }

        CleanUpChangeWatchers();    
       }    


    private static void ondeleted(object source, RenamedEventArgs e){ 
        CleanUpChangeWatchers();
        watcher.Dispose();

        while(!directoryRecreated(file)){
            Thread.Sleep(...some delay..);
        }
        SetUpChangeWatchers();  
        watcher = new Watcher("somedir", ondeleted);

    }
}

You can handle this with the .deleted event. 您可以使用.deleted事件处理此事件。 However, if you delete the directory assigned to the filesystemwatcher.Path, it may cause an error. 但是,如果删除分配给filesystemwatcher.Path的目录,则可能会导致错误。 One way around this is to assign the parent of the watched directory to filesystemwatcher.Path. 解决此问题的一种方法是将监视目录的父目录分配给filesystemwatcher.Path。 Then it should catch the deletion in the .deleted event. 然后,它应该在.deleted事件中捕获删除。

It is also possible to have an error inside the handler if you try to access the directory just deleted. 如果您尝试访问刚刚删除的目录,则处理程序中也可能出现错误。 When this happens, you may not get the normal breakpoint and it seems like it's caused by the deletion itself. 发生这种情况时,您可能无法获得正常的断点,这似乎是由删除本身引起的。

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

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