MyFileSystemWatcherService 繼承 ServiceBase,核心啟動方法 StartFileSystemWatching:
private ArrayList myWatchers = null;
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;
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();
}