【发布时间】:2018-06-22 03:42:05
【问题描述】:
我正在尝试使用 FileSystemWatcher 创建一个服务来检测我的 C 驱动器中的一些更改。
以下代码没有触发,我不知道为什么。
FileSystemWatcher watcher;
protected override void OnStart(string[] args)
{
trackFileSystemChanges();
watcher.EnableRaisingEvents = true;
}
trackFileSystemChanges() 方法基本上设置观察者来观察 LastWrite 和 LastAccess 时间的变化,目录中文本文件的创建、删除或重命名。
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public void trackFileSystemChanges()
{
watcher = new FileSystemWatcher();
watcher.Path = @"C:\";
Library.WriteErrorLog(watcher.Path);
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.Filter = "*.*";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
}
当 txt 文件被更改或重命名时,日志被写入文件。
private static void OnChanged(object source, FileSystemEventArgs e)
{
// Specify what is done when a file is changed, created, or deleted.
Library.WriteErrorLog("File: " + e.FullPath + " " + e.ChangeType);
}
private static void OnRenamed(object source, RenamedEventArgs e)
{
// Specify what is done when a file is renamed.
Library.WriteErrorLog("File: " + e.OldFullPath + "renamed to " + e.FullPath);
}
Library.WriteErrorLog 方法没有问题,因为我已经用其他东西对其进行了测试。当服务启动时,当我尝试在我的 C 驱动器中编辑/重命名一些 txt 文件时,没有任何记录。
【问题讨论】:
-
您是否先在控制台应用中尝试过此操作?
-
服务是否以具有文件系统权限的用户身份运行,例如 SYSTEM?
-
@Josh 如果 "SYSTEM" 你的意思是
Local System那么 a) 它不是 "user" 和 b) "Completely trusted account, more so than the administrator account. There is nothing on a single box that this account cannot do, and it has the right to access the network as the machine (this requires Active Directory and granting the machine account permissions to something)" -
顺便说一句,
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]实际上并没有对提升或确保您的代码在该 CAS 级别上运行做任何事情,需要先查找它并在AppDomain为时授予它创建的。 FSW 很可能正在执行一个明确的 CAS 要求,如果调用链不满足,该要求就会出错。
标签: c# service filesystemwatcher