c# - 在 C# 中将计时器与 fileSystemWatcher 一起使用

标签 c# .net reset filesystemwatcher system.timers.timer

场景是我有一个根文件夹来监视任何新文件夹(包含文件)并设置一个计时器来单独压缩每个文件夹。但是,在调用 zip 函数之前,我无法判断文件夹中的文件是否是最后一个文件,因此我想在压缩文件夹之前创建新文件时将计时器重置为该文件夹。

我使用 FileSystemWatcher 来监控根文件夹及其子文件夹。

  1. 我不确定如何创建另一个观察器来监视文件创建,也许是在 OnTimedEvent 方法中。
  2. 一旦检测到该文件夹​​的文件,我不知道如何重置计时器。我的想法也是在 OnTimedEvent 中编写代码来重置它。

下面是我尝试的部分代码,源代码可以找到here .任何帮助将不胜感激。

    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??
    }

最佳答案

这里有一个简单的扩展方法来重置给定的计时器。

  public static void Reset(this Timer timer)
    {
      timer.Stop();
      timer.Start();
    }

要从事件内部获取计时器对象,您需要将 sender 转换为 System.Timers.Timer() 或仅在静态上下文中使用计时器。

关于c# - 在 C# 中将计时器与 fileSystemWatcher 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53084587/

相关文章:

c# - 计划和取消任务列表

c# - 未调用 ASP.NET 组合 selectedIndexChanged 事件

reset - 为什么不能重置 IFS 变量?

c# - 具有内部属性的 JSON Serializer 对象

c# - 分割太长的字符串

c# - 外键引用在分配 Null 时已具有值异常 Linq to SQL

c# - ContentDialog showAsync() 给出错误 : no definition for getAwaiter

c# - 如何创建以点为前缀的 cookie uri?

css - 删除/完全重置 img 上的继承样式

C++11 将结构重置为 null 的方法?