【问题标题】:C# FileSystemWatcher not triggering when used in a ServiceC# FileSystemWatcher 在服务中使用时未触发
【发布时间】: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 文件时,没有任何记录。

【问题讨论】:

标签: c# service filesystemwatcher


【解决方案1】:

添加到SengokuMedaru's answerFileSystemWatcher 默认情况下包含子文件夹,因此如果您:

watcher.Path = @"C:\";

...对 C:\Users\User1\ConfidentialFiles 的更改将不会被报告

你有两个选择。

  1. 指定明确的根文件夹,您知道文件将在其中更改并感兴趣。即watcher.Path = @"C:\Users\User1\ConfidentialFiles";(可以根据需要设置IncludeSubdirectories)或...

  2. IncludeSubdirectories 设置为true


注意但是,将IncludeSubdirectories 设置为truewatcher.Path = @"c:\"; 是不可取的,因为您将遇到大量流量(并且会因被截断而受到摆布缓冲限制)


MSDN:

当您想要监视通过 Path 属性指定的目录及其子目录中包含的文件和目录的更改通知时,请将 IncludeSubdirectories 设置为 true。将 IncludeSubdirectories 属性设置为 false 有助于减少发送到内部缓冲区的通知数量。有关过滤掉不需要的通知的详细信息,请参阅 NotifyFilter 和 InternalBufferSize 属性。 More...

【讨论】:

    【解决方案2】:

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

    例如:

     watcher.Path = @"C:\Users\User1\ConfidentialFiles";
    

    【讨论】:

    • 但您已经将其设置为C:。如何解释它适用于子文件夹而不适用于整个 C 盘?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多