Search code examples
c#.netresetfilesystemwatchersystem.timers.timer

Use timer with fileSystemWatcher in C#


The scenario is that I have a root folder to monitor any new folder (that contains files) and set a timer to zip each of them individually. However, I can't tell if the file in the folder is the last file before calling the zip function, and therefore I want to reset a timer to that folder, whenever there is a new file created before zipping the folder.

I using FileSystemWatcher to monitor both root folder and its sub-folders.

  1. I'm not sure how to create another watcher to monitor the file creation, perhaps in the OnTimedEvent method.
  2. I don't know how to reset the timer once detect a file of that folder. What I think is also write the code in the OnTimedEvent to reset it.

Below is part of my attempted code and the source code can be found here. Any help will be highly appreciated.

    public class FileWatcher
    { 
     private FileSystemWatcher _watcherRoot;
     private Timer _timer;
     private readonly string _watchedPath;

    public FileWatcher(string path)
    {
        // _watcher = new FileSystemWatcher();
        _timer = new Timer();
        _watchedPath = path;


        InitWatcher();
    }

    public void InitWatcher()
    {
        _watcherRoot = new FileSystemWatcher();
        _watcherRoot.Path = _watchedPath;
        _watcherRoot.IncludeSubdirectories = true;
        _watcherRoot.EnableRaisingEvents = true;
        _watcherRoot.Created += new FileSystemEventHandler(OnCreated);

    }

    private void OnCreated(object sender, FileSystemEventArgs e)
    {

        if (e.ChangeType == WatcherChangeTypes.Created)
        {
            string fullPath = e.FullPath;
            if (sender == _watcherRoot)
            {
                // If detect new folder, set the timer to 5 sec
                _timer.Interval = 5000;
                _timer.Elapsed += OnTimedEvent;
                _timer.AutoReset = true;
                _timer.Enabled = true;

                // a directory
                Console.WriteLine($"{fullPath.ToString()} created on {DateTime.Now}");
            }

        }
    }

    private void OnTimedEvent(object sender, ElapsedEventArgs e)
    {
        // Create a 2nd Watcher??
        // Reset the timer in here??
    }

Solution

  • I sort of using the lambda expression to solve this issue as "binding" the timer and watcher together and this is what I found similar to this post.