简体   繁体   中英

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.

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?

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. However, if you delete the directory assigned to the filesystemwatcher.Path, it may cause an error. One way around this is to assign the parent of the watched directory to filesystemwatcher.Path. Then it should catch the deletion in the .deleted event.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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