FileSystemWatcher不会在具有托管服务的控制台应用程序中触发Linux上的事件

问题描述

您好,我目前正在尝试在运行托管服务的控制台应用程序中实现FileSystemWatcher,但似乎无法获得在文件系统发生更改时触发事件的实现。

这是我的控制台应用程序的program.cs中的代码示例。

await new HostBuilder().ConfigureServices((hostContext,services) => { services.AddHostedService<MyTestService>(); }).runconsoleAsync();

然后在MyTestService中,我有一个StartupService.cs,在其Startup方法中包含以下代码

var watcher = new FileSystemWatcher()
var fileWatcherDirectoryPath = ConfigurationManager.AppSettings["FileWatcherDirectoryPath"];
watcher.Path = fileWatcherDirectoryPath;        
    
// Watch for changes in LastAccess and LastWrite times,and
// the renaming of files or directories.
watcher.NotifyFilter = NotifyFilters.LastAccess
    | NotifyFilters.LastWrite
    | NotifyFilters.FileName
    | NotifyFilters.DirectoryName;
    
watcher.Filter = "*.*";
    
// Add event handlers.
watcher.Changed += OnChanged;
watcher.Created += OnChanged;
watcher.Deleted += OnChanged;
watcher.Renamed += OnRenamed;
    
// Begin watching.
watcher.EnableRaisingEvents = true;

private static void OnChanged(object source,FileSystemEventArgs e) =>
    // Specify what is done when a file is changed,created,or deleted.
    Console.WriteLine($"File: {e.FullPath} {e.ChangeType}");

private static void OnRenamed(object source,RenamedEventArgs e) =>
    // Specify what is done when a file is renamed.
    Console.WriteLine($"File: {e.OldFullPath} renamed to {e.FullPath}");

我从下面链接中找到的Microsoft文档中提取一个简单的应用程序,并且能够在独立的控制台应用程序中运行该应用程序,但是未能使其与托管服务一起使用。我当然删除了using语句,但是我认为一旦托管服务启动,观察程序就永远不会收到事件,因此不确定为什么,因为我认为它运行了自己的线程。我们将不胜感激为我指明正确方向并解决此问题的任何帮助。

https://docs.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher?view=netcore-3.1

解决方法

因此希望这对其他人有所帮助,但这是一个范围变量问题。当我将FileSystemWatcher设置为服务类中的私有字段时,它起作用了。