Using FileSystemWatcher with multiple files

后端 未结 4 1220
小蘑菇
小蘑菇 2020-12-16 03:27

I want to use FileSystemWatcher to monitor a directory and its subdirectories for files that are moved. And then I want to trigger some code when all the files have been mov

4条回答
  •  情深已故
    2020-12-16 04:16

    I had to do the exact same thing. Use a System.Timers.Timer in your Monitor class and code its Elapsed event to process your List of files and clear the List. When the first item is added to your file List via the FSW events, start the Timer. When subsequent items are added to the list 'reset' the Timer by stopping and restarting it.

    Something like this:

    class Monitor
    {
        FileSystemWatcher _fsw;
        Timer _notificationTimer;
        List _filePaths = new List();
    
        public Monitor() {
            _notificationTimer = new Timer();
            _notificationTimer.Elapsed += notificationTimer_Elapsed;
            // CooldownSeconds is the number of seconds the Timer is 'extended' each time a file is added.
            // I found it convenient to put this value in an app config file.
            _notificationTimer.Interval = CooldownSeconds * 1000;
    
            _fsw = new FileSystemWatcher();
            // Set up the particulars of your FileSystemWatcher.
            _fsw.Created += fsw_Created;
        }
    
        private void notificationTimer_Elapsed(object sender, ElapsedEventArgs e) {
            //
            // Do what you want to do with your List of files.
            //
    
            // Stop the timer and wait for the next batch of files.            
            _notificationTimer.Stop();
            // Clear your file List.
            _filePaths = new List();
        }
    
    
        // Fires when a file is created.
        private void fsw_Created(object sender, FileSystemEventArgs e) {
            // Add to our List of files.
            _filePaths.Add(e.Name);
    
            // 'Reset' timer.
            _notificationTimer.Stop();
            _notificationTimer.Start();
        }
    }
    

提交回复
热议问题