文件系統監視服務 MyFileSystemWatcherService
類MyFileSystemWatcherService就是文件系統監視服務 ,它是從ServiceBase派生的,首先說明一下執行文件系統監視的功能性的過程,其代碼如下
/// <summary>
/// 文件系統監視器列表
/// </summary>
private System.Collections.ArrayList myWatchers = null;
/// <summary>
/// 開始啟動文件系統監視
/// </summary>
/// <returns>操作是否成功</returns>
internal bool StartFileSystemWatching()
{
myWatchers = new System.Collections.ArrayList();
MyConfig.Instance.Load();
string[] paths = MyConfig.Instance.WatchedPaths;
System.Text.StringBuilder myPathList = new StringBuilder();
if (paths != null)
{
foreach (string path in paths)
{
if (System.IO.Path.IsPathRooted(path) == false)
{
continue;
}
string BasePath = null;
string Filter = null;
if (System.IO.Directory.Exists(path))
{
BasePath = path;
Filter = "*.*";
}
else
{
BasePath = System.IO.Path.GetDirectoryName (path);
Filter = System.IO.Path.GetFileName(path);
}
if (BasePath == null)
{
continue;
}
BasePath = BasePath.Trim();
if (BasePath.ToUpper().StartsWith (System.Windows.Forms.Application.StartupPath))
{
// 不能監視程序本身所在的目錄的文件系統更改
continue;
}
if (System.IO.Directory.Exists(BasePath) == false)
{
// 不能監視不存在的目錄
continue;
}
if (myPathList.Length > 0)
{
myPathList.Append(";");
}
myPathList.Append(path);
System.IO.FileSystemWatcher watcher = new System.IO.FileSystemWatcher();
watcher.Path = BasePath;
watcher.Filter = Filter;
watcher.EnableRaisingEvents = true;
watcher.IncludeSubdirectorIEs = false;
if (MyConfig.Instance.LogChanged)
{
watcher.Changed += delegate(object sender, System.IO.FileSystemEventArgs args)
{
WriteFileSystemLog(args.FullPath, args.ChangeType.ToString());
};
}
if (MyConfig.Instance.LogCreated)
{
watcher.Created += delegate(object sender, System.IO.FileSystemEventArgs args)
{
WriteFileSystemLog(args.FullPath, args.ChangeType.ToString());
};
}
if (MyConfig.Instance.LogDeleted)
{
watcher.Deleted += delegate(object sender, System.IO.FileSystemEventArgs args)
{
WriteFileSystemLog(args.FullPath, args.ChangeType.ToString());
};
}
if (MyConfig.Instance.LogRenamed)
{
watcher.Renamed += delegate(object sender, System.IO.RenamedEventArgs args)
{
WriteFileSystemLog(args.FullPath, args.ChangeType.ToString());
};
}
myWatchers.Add(watcher);
}//foreach
this.EventLog.WriteEntry(
"開始監視文件系統 " + myPathList.ToString(),
EventLogEntryType.Information);
}//if
return true;
}