C# 文件系统观察程序在服务中使用时不触发



我正在尝试使用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 文件时,不会记录任何内容。

除了SengokuMedaru的答案之外,默认情况下,FileSystemWatcher不包括子文件夹,因此如果您:

watcher.Path = @"C:";

。不会报告C:\Users\User1\ConfidentialFiles的更改。

您有两个选择。

  1. 指定您知道文件将要更改并感兴趣的显式根文件夹,即watcher.Path = @"C:UsersUser1ConfidentialFiles";(根据您的需要IncludeSubdirectories设置(或...

  2. IncludeSubdirectories设置为true


请注意,由于您将遇到大量流量,因此不建议将IncludeSubdirectories设置为watcher.Path = @"c:";true(并且由于缓冲区限制而被截断(


MSDN:

如果要监视通过 Path 属性指定的目录及其子目录中包含的文件和目录的更改通知,请将 IncludeSubdirectory 设置为 true。将"包含子目录"属性设置为 false 有助于减少发送到内部缓冲区的通知数。有关筛选出不需要的通知的详细信息,请参阅 NotifyFilter 和 InternalBufferSize 属性。更多。。。

我找到了一个解决方案,那就是明确说明我试图在其中查找文件更改的目录。否则由于某种原因,它将无法正常工作。

例如:

watcher.Path = @"C:UsersUser1ConfidentialFiles";

最新更新