I hope this can help you as a starting point. And you may want to read about this bug in FileSystemWatcher
class
using System;
using System.IO;
namespace Tools
{
public class AutoBackupFSW
{
private string _fileDestination;
private DateTime _lastBackUp;
public delegate void BackUpDone(string filePath);
public event BackUpDone OnBackUpDone;
public AutoBackupFSW(string directory, string fileDestination)
{
_fileDestination = fileDestination;
_lastBackUp = DateTime.Now;
FileSystemWatcher fsw = new FileSystemWatcher(directory, "*.txt");
fsw.EnableRaisingEvents = true;
fsw.IncludeSubdirectories = false;
fsw.NotifyFilter = NotifyFilters.LastWrite;
fsw.Changed += Fsw_Changed;
}
private void Fsw_Changed(object sender, FileSystemEventArgs e)
{
using (FileStream fs = new FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
File.WriteAllBytes(_fileDestination, buffer);
}
if ((DateTime.Now - _lastBackUp).TotalSeconds > 1 && e.ChangeType == WatcherChangeTypes.Changed)
OnBackUpDone?.Invoke(e.FullPath);
_lastBackUp = DateTime.Now;
}
}
}
and usage:
AutoBackupFSW fs = new AutoBackupFSW(@"F:\test", @"F:\fws\mydoc_backup.txt");
fs.OnBackUpDone += BackUpEngine_OnBackUpDone;
private void BackUpEngine_OnBackUpDone(string filePath)
{
BeginInvoke(new Action(() =>
{
richTextBox1.Text += $"[BACK_UP_LOG]: Back up done at {DateTime.Now.ToShortTimeString()}\r\n";
}));
}