如何使用C#实现文本文件内容变更时自动备份至指定位置
C#实现文件变更自动备份方案
核心思路
使用.NET自带的FileSystemWatcher组件监听目标文件的内容变更事件,当检测到文件修改时,立即将文件备份到指定目录,通过时间戳+原文件名的命名规则留存每次变更的版本,同时处理文件被占用、重复触发等常见问题。
完整代码示例
using System; using System.IO; using System.Timers; class FileBackupMonitor { private readonly FileSystemWatcher _watcher; private readonly string _targetFilePath; private readonly string _backupDirPath; private Timer _debounceTimer; private const int DebounceDelayMs = 2000; // 防抖延迟,避免重复触发 public FileBackupMonitor(string targetFilePath, string backupDirPath) { _targetFilePath = targetFilePath; _backupDirPath = backupDirPath; // 确保备份目录存在 Directory.CreateDirectory(_backupDirPath); // 初始化文件监听器 _watcher = new FileSystemWatcher(Path.GetDirectoryName(targetFilePath)) { Filter = Path.GetFileName(targetFilePath), NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size, // 监听文件写入和大小变化 EnableRaisingEvents = true }; // 绑定变更事件 _watcher.Changed += OnFileChanged; // 初始化防抖定时器 _debounceTimer = new Timer(DebounceDelayMs) { AutoReset = false }; _debounceTimer.Elapsed += PerformBackup; } private void OnFileChanged(object sender, FileSystemEventArgs e) { // 重置防抖定时器,避免短时间内多次触发备份 _debounceTimer.Stop(); _debounceTimer.Start(); } private void PerformBackup(object sender, ElapsedEventArgs e) { try { // 处理文件被占用的情况,最多重试3次 for (int retry = 0; retry < 3; retry++) { try { string timestamp = DateTime.Now.ToString("yyyyMMddHHmmssfff"); string backupFileName = $"{Path.GetFileNameWithoutExtension(_targetFilePath)}_{timestamp}{Path.GetExtension(_targetFilePath)}"; string backupFilePath = Path.Combine(_backupDirPath, backupFileName); // 复制文件到备份目录 File.Copy(_targetFilePath, backupFilePath, overwrite: false); Console.WriteLine($"备份成功:{backupFilePath}"); break; } catch (IOException) { // 文件被占用,等待1秒后重试 System.Threading.Thread.Sleep(1000); if (retry == 2) { Console.WriteLine("重试3次后仍无法访问文件,备份失败"); } } } } catch (Exception ex) { Console.WriteLine($"备份过程出错:{ex.Message}"); } } public void StartMonitoring() { Console.WriteLine($"开始监控文件:{_targetFilePath}"); Console.WriteLine("按任意键停止监控..."); Console.ReadKey(); _watcher.EnableRaisingEvents = false; _watcher.Dispose(); _debounceTimer.Dispose(); } static void Main(string[] args) { // 替换为你的目标文件路径和备份目录路径 string targetFile = @"C:\SystemFiles\Target.txt"; string backupDir = @"C:\FileBackups"; var monitor = new FileBackupMonitor(targetFile, backupDir); monitor.StartMonitoring(); } }
关键细节说明
- 防抖机制:设置
DebounceDelayMs延迟执行备份,避免某些程序写入文件时多次触发Changed事件导致重复备份。 - 文件占用处理:通过循环重试+延迟的方式,解决目标文件被系统程序占用无法读取的问题。
- 备份命名规则:使用精确到毫秒的时间戳,确保每次备份的文件名唯一,不会覆盖旧版本。
- 异常捕获:捕获IO异常和通用异常,避免程序因单次备份失败而崩溃。
扩展建议
- 如果需要长期后台运行,可以将程序改造为Windows服务,或者使用.NET Worker Service。
- 添加日志记录功能,将备份成功/失败的信息写入日志文件,方便后续排查。
- 配置备份保留策略,比如自动删除超过N天的旧备份,避免磁盘空间被占满。
内容的提问来源于stack exchange,提问作者noura
相关产品推荐
相关产品推荐

