场景是我有一个根文件夹来监视任何新文件夹(包含文件)并设置一个计时器来单独压缩每个文件夹。但是,我无法判断文件夹中的文件是否是调用 zip 函数之前的最后一个文件,因此,只要在压缩文件夹之前创建了新文件,我就想将计时器重置到该文件夹。
我FileSystemWatcher
用来监视根文件夹及其子文件夹。
- 我不确定如何创建另一个观察者来监视文件的创建,也许是在 OnTimedEvent 方法中。
- 一旦检测到该文件夹的文件,我不知道如何重置计时器。我认为也是在 OnTimedEvent 中编写代码来重置它。
下面是我尝试的代码的一部分,源代码可以在这里找到。任何帮助将不胜感激。
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??
}