核心類別:FileSystemWatcher
System.IO.FileSystemWatcher 訂閱作業系統檔案系統通知(Windows 基於 ReadDirectoryChangesW),當指定目錄發生建立、刪除、修改、重命名事件時觸發對應事件。支援本機、網路磁碟、遠端電腦(需權限)。
關鍵屬性設定
| 屬性 | 型別 | 預設 | 說明 |
| Path | string | "" | 監控目錄完整路徑 |
| Filter | string | "*.*" | 檔名篩選(支援萬用字元),如 "*.txt"、"log_*.csv" |
| NotifyFilter | NotifyFilters | LastWrite | FileName | DirectoryName | 位元旗標組合:Attributes、CreationTime、LastAccess、LastWrite、Size、Security、FileName、DirectoryName |
| IncludeSubdirectories | bool | false | true 遞迴監控子目錄 |
| EnableRaisingEvents | bool | false | true 啟動監控(必須最後設定) |
| InternalBufferSize | int | 8192 (8KB) | 內部緩衝區大小(4KB~64KB),事件暴增時防溢位;過大佔用非分頁記憶體 |
事件與事件引數
| 事件 | 引數型別 | 觸發時機 |
| Created | FileSystemEventArgs | 檔案/目錄建立 |
| Deleted | FileSystemEventArgs | 檔案/目錄刪除 |
| Changed | FileSystemEventArgs | 內容/屬性/大小變更(儲存、覆寫、屬性修改) |
| Renamed | RenamedEventArgs | 重命名/移動(含 OldFullPath、OldName) |
| Error | ErrorEventArgs | 緩衝區溢位或系統錯誤(需重新啟動監控) |
完整封裝類別:FileWatcher
using System;
using System.IO;
using System.Collections.Generic;
public class FileChangeInfo {
public DateTime Time { get; set; }
public WatcherChangeTypes ChangeType { get; set; }
public string FullPath { get; set; }
public string OldFullPath { get; set; } // 僅 Renamed 使用
public override string ToString() => $"{Time:yyyy-MM-dd HH:mm:ss} [{ChangeType}] {FullPath}" + (OldFullPath != null ? $" <- {OldFullPath}" : "");
}
public class FileWatcher : IDisposable {
private readonly FileSystemWatcher _watcher;
private readonly Queue _queue = new Queue();
private readonly object _lock = new object();
private readonly string _persistPath;
private readonly Timer _persistTimer;
public FileWatcher(string path, string filter = "*.*", bool includeSubdirs = true, string persistPath = null) {
_watcher = new FileSystemWatcher(path, filter) {
IncludeSubdirectories = includeSubdirs,
NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite | NotifyFilters.Size | NotifyFilters.Attributes,
EnableRaisingEvents = true
};
_watcher.Created += OnChanged;
_watcher.Changed += OnChanged;
_watcher.Deleted += OnChanged;
_watcher.Renamed += OnRenamed;
_watcher.Error += OnError;
_persistPath = persistPath;
if (!string.IsNullOrEmpty(_persistPath)) {
_persistTimer = new Timer(_ => Persist(), null, TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(30));
LoadPersisted();
}
}
private void OnChanged(object sender, FileSystemEventArgs e) {
Enqueue(new FileChangeInfo { Time = DateTime.Now, ChangeType = e.ChangeType, FullPath = e.FullPath });
}
private void OnRenamed(object sender, RenamedEventArgs e) {
Enqueue(new FileChangeInfo { Time = DateTime.Now, ChangeType = e.ChangeType, FullPath = e.FullPath, OldFullPath = e.OldFullPath });
}
private void OnError(object sender, ErrorEventArgs e) {
// 緩衝區溢位:重新啟動監控
_watcher.EnableRaisingEvents = false;
_watcher.EnableRaisingEvents = true;
Enqueue(new FileChangeInfo { Time = DateTime.Now, ChangeType = WatcherChangeTypes.All, FullPath = "[ERROR] " + e.GetException().Message });
}
private void Enqueue(FileChangeInfo info) {
lock (_lock) { _queue.Enqueue(info); }
}
public IEnumerable DequeueAll() {
lock (_lock) {
while (_queue.Count > 0) yield return _queue.Dequeue();
}
}
private void Persist() {
lock (_lock) {
if (_queue.Count == 0) return;
File.AppendAllLines(_persistPath, _queue.ConvertAll(i => i.ToString()));
_queue.Clear();
}
}
private void LoadPersisted() {
if (File.Exists(_persistPath)) {
foreach (var line in File.ReadAllLines(_persistPath)) {
// 簡易解析,實際建議用 JSON 序列化
_queue.Enqueue(new FileChangeInfo { FullPath = line });
}
File.Delete(_persistPath);
}
}
public void Dispose() {
_watcher.EnableRaisingEvents = false;
_watcher.Dispose();
_persistTimer?.Dispose();
Persist();
}
}
使用範例
static void Main() {
using (var watcher = new FileWatcher(@"D:\WatchFolder", "*.txt", true, @"D:\WatchFolder\log.txt")) {
Console.WriteLine("監控已啟動,按 Enter 結束...");
var timer = new System.Timers.Timer(1000);
timer.Elapsed += (s, e) => {
foreach (var info in watcher.DequeueAll()) {
Console.WriteLine(info);
// 這裡可觸發業務邏輯:同步上傳、資料庫寫入、發送通知等
}
};
timer.Start();
Console.ReadLine();
}
}
進階避坑指南
- 事件重複觸發:儲存檔案常觸發多次
Changed(寫入、屬性更新)。解法:去抖動(Debounce),如用 ConcurrentDictionary 記錄最後處理時間,間隔 < 500ms 忽略。
- 網路磁碟監控:SMB 共享需確保雙向通訊正常,防火牆開啟 File and Printer Sharing;緩衝區建議調大至 32KB。
- 大量檔案操作:短時間大量建立/刪除會導致
Error 事件(緩衝區溢位)。啟用 IncludeSubdirectories=false 縮小範圍,或分多個 Watcher 監控不同子目錄。
- 權限問題:服務帳號需具備目錄「列出資料夾/讀取資料」權限;網路路徑需具備對應網路憑證。
- 跨平台:.NET Core / .NET 5+ 在 Linux/macOS 使用
inotify/FSEvents/kqueue,行為一致但細節不同(如 rename 事件細節),測試時需實測目標平台。