首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 開發 Windows Service 程序(下):檔案系統監視服務核心實作與事件處理

     編輯:關於C語言

StartFileSystemWatching 核心邏輯

載入設定、解析路徑、建立 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();
    }
}

ServiceBase 覆寫方法

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 同理可擴充暫停/繼續監視邏輯。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved