gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:39:27 28 4
gpt4 key购买 nike

场景是我有一个根文件夹来监视任何新文件夹(包含文件)并设置一个计时器来单独压缩每个文件夹。但是,在调用 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com