Обзор:
Я создал две FileSystemWatcher
для обнаружения подпапок и создания их файлов. Я также использую Timer
для второго наблюдателя (наблюдателя файлов), который перезапускает таймер для каждого файла, созданного в любой папке, перед динамическим вызовом метода zip.
Я пытаюсь выполнить этот процесс для каждой папки, но он архивирует все папки сразу, независимо от того, есть ли файл, перемещающийся в эти папки.
Ниже приведена часть моего кода для имитации процесса таймера и zip ... У меня может возникнуть проблема с перемещением zip-файла в корневую папку при вызове метода zip.
Таймер внутри файла Watcher
namespace ZipperAndWatcher
{
public class Archive
{
public void CreateZip(string path)
{
// zip method code
}
}
public class FileWatcher
{
private FileSystemWatcher _fsw;
private Archive _zip;
private string _path;
private Timer _timer;
public FileWatcher()
{
_fsw = new FileSystemWatcher();
_zip = new Archive();
_path = @"D:\Documents\output";
_timer = new Timer();
}
public void StartWatching()
{
var rootWatcher = _fsw;
rootWatcher.Path = _path;
rootWatcher.Created += new FileSystemEventHandler(OnRootFolderCreated);
rootWatcher.EnableRaisingEvents = true;
rootWatcher.Filter = "*.*";
}
private void OnRootFolderCreated(object sender, FileSystemEventArgs e)
{
string watchedPath = e.FullPath; // watched path
// create another watcher for file creation and send event to timer
FileSystemWatcher subFolderWatcher = new FileSystemWatcher();
subFolderWatcher.Path = watchedPath + @"\";
// Timer setting
var aTimer = _timer;
aTimer.Interval = 20000;
// Lambda == args => expression
// send event to subFolderWatcher
aTimer.Elapsed += new ElapsedEventHandler((subfolderSender, evt) => OnTimedEvent(subfolderSender, evt, subFolderWatcher));
aTimer.AutoReset = false;
aTimer.Enabled = true;
// sub-folder sends event to timer (and wait timer to notify subfolder)
subFolderWatcher.Created += new FileSystemEventHandler((s, evt) => subFolderWatcher_Created(s, evt, aTimer));
subFolderWatcher.Filter = "*.*";
subFolderWatcher.EnableRaisingEvents = true;
}
private void OnTimedEvent(object sender, ElapsedEventArgs evt, FileSystemWatcher subFolderWatcher)
{
subFolderWatcher.EnableRaisingEvents = false;
// Explicit Casting
Timer timer = sender as Timer;
timer.Stop();
timer.Dispose();
// Once time elapsed, zip the folder here?
Console.WriteLine($"time up. zip process at {evt.SignalTime}");
Archive zip = _zip;
zip.CreateZip(subFolderWatcher.Path.Substring(0, subFolderWatcher.Path.LastIndexOf(@"\")));
subFolderWatcher.Dispose();
}
private void subFolderWatcher_Created(object sender, FileSystemEventArgs evt, Timer aTimer)
{
// if new file created, stop the timer
// then restart the timer
aTimer.AutoReset = false;
aTimer.Stop();
aTimer.Start();
Console.WriteLine($"restart the timer as {evt.Name} created on {DateTime.Now.ToString()}");
}
}
}