載入設定、解析路徑、建立 FileSystemWatcher、綁定事件、加入監視清單:
internal bool StartFileSystemWatching() {
myWatchers = new ArrayList();
MyConfig.Instance.Load();
string[] paths = MyConfig.Instance.WatchedPaths;
StringBuilder pathList = new StringBuilder();
if (paths != null) {
foreach (string path in paths) {
if (!Path.IsPathRooted(path)) continue;
string basePath, filter;
if (Directory.Exists(path)) {
basePath = path; filter = "*.*";
} else {
basePath = Path.GetDirectoryName(path);
filter = Path.GetFileName(path);
}
if (basePath == null) continue;
basePath = basePath.Trim();
// 避免監視程式自身目錄
if (basePath.ToUpper().StartsWith(Application.StartupPath.ToUpper())) continue;
if (!Directory.Exists(basePath)) continue;
if (pathList.Length > 0) pathList.Append(";");
pathList.Append(path);
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = basePath;
watcher.Filter = filter;
watcher.EnableRaisingEvents = true;
watcher.IncludeSubdirectories = false;
// 使用 C# 2.0 匿名委派綁定事件
if (MyConfig.Instance.LogChanged)
watcher.Changed += (s, e) => WriteFileSystemLog(e.FullPath, e.ChangeType.ToString());
if (MyConfig.Instance.LogCreated)
watcher.Created += (s, e) => WriteFileSystemLog(e.FullPath, e.ChangeType.ToString());
if (MyConfig.Instance.LogDeleted)
watcher.Deleted += (s, e) => WriteFileSystemLog(e.FullPath, e.ChangeType.ToString());
if (MyConfig.Instance.LogRenamed)
watcher.Renamed += (s, e) => WriteFileSystemLog(e.FullPath, e.ChangeType.ToString());
myWatchers.Add(watcher);
}
EventLog.WriteEntry("開始監視檔案系統 " + pathList, EventLogEntryType.Information);
}
return true;
}
private void WriteFileSystemLog(string objectName, string eventStyle) {
IDbConnection conn = Util.DBConnection;
if (conn == null) return;
using (IDbCommand cmd = conn.CreateCommand()) {
cmd.CommandText = "INSERT INTO FileSystemLog (RecordID, WatchTime, ObjectName, EventStyle) VALUES ('"
+ Guid.NewGuid() + "', '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "', ?, '" + eventStyle + "')";
IDbDataParameter p = cmd.CreateParameter();
p.Value = objectName;
cmd.Parameters.Add(p);
cmd.ExecuteNonQuery();
}
}
protected override void OnStart(string[] args) {
StartFileSystemWatching();
}
protected override void OnStop() {
if (myWatchers != null) {
foreach (FileSystemWatcher w in myWatchers) {
w.EnableRaisingEvents = false;
w.Dispose();
}
myWatchers = null;
}
Util.CloseDBConnection();
base.OnStop();
}
OnPause/OnContinue 同理可擴充暫停/繼續監視邏輯。