C# FileSystemWatcher 在服务中使用时不触发

C# FileSystemWatcher not triggering when used in a Service

我正在尝试使用 FileSystemWatcher 创建一个服务来检测我的 C 驱动器中的一些变化。

下面的代码没有触发,我也不知道为什么。

FileSystemWatcher watcher;

    protected override void OnStart(string[] args)
    {
        trackFileSystemChanges();
        watcher.EnableRaisingEvents = true;
    }

trackFileSystemChanges() 方法主要是设置 watcher 以监视 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 方法没有问题,因为我用其他东西测试过它。当服务启动时,当我尝试 editing/renaming 我的 C 驱动器中的一些 txt 文件时,没有任何记录。

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

例如:

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

添加到 SengokuMedaru's FileSystemWatcher 默认 包括 子文件夹 所以如果你:

watcher.Path = @"C:\";

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

你有两个选择。

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

  2. IncludeSubdirectories 设置为 true


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


MSDN:

Set IncludeSubdirectories to true when you want to watch for change notifications for files and directories contained within the directory specified through the Path property, and its subdirectories. Setting the IncludeSubdirectories property to false helps reduce the number of notifications sent to the internal buffer. For more information on filtering out unwanted notifications, see the NotifyFilter and InternalBufferSize properties. More...