c# - 如何在具有 .NET 5.0+ 的 Linux 上使用 FileSystemWatcher
问题描述
我正在尝试使用 FileSystemWatcher 类监视指定目录中的更改。很大程度上基于MS docs上的示例,该示例在我的 Windows 机器上运行良好。但问题是,我的目标是 Ubtuntu 18.04 及更高版本来运行它。观察者显然设置得很好(代码执行和控制台/日志消息被打印出来)但没有任何文件系统事件被触发,即:更改/创建/删除/重命名/等没有触发这些事件。
是否有任何未记录或“隐藏”的设置细节需要与 Linux 一起使用,或者完全不支持它,即使它在 .NET 5 中也不应该用于 Linux/Mac/Unix 构建?我找不到任何关于非 Windows 使用的权威文档,但我认为 .NET 5 旨在“便携”地工作。任何提示/细节将不胜感激,因为我相信其他人也遇到过这个问题,或者至少有可能遇到过。
当前适用于 Windows 构建但不适用于 Linux 的代码:
public void WatchFolder()
{
string directoryPath = _configuration["FolderLocation"];
if (string.IsNullOrWhiteSpace(directoryPath))
throw new Exception("Folder location was not set.");
try
{
// setup file system watcher
using var watcher = new FileSystemWatcher(directoryPath);
watcher.NotifyFilter = NotifyFilters.Attributes
| NotifyFilters.CreationTime
| NotifyFilters.DirectoryName
| NotifyFilters.FileName
| NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.Security
| NotifyFilters.Size;
// add handler methods
watcher.Changed += OnChanged;
watcher.Created += OnCreated;
watcher.Deleted += OnDeleted;
watcher.Renamed += OnRenamed;
watcher.Error += OnError;
watcher.IncludeSubdirectories = true;
watcher.EnableRaisingEvents = true;
// wait for next key to kill execution
Console.ReadLine();
}
catch (Exception ex)
{
_logger.LogError($"Couldn't watch folder: {directoryPath}\nBecause: {ex}");
}
}
编辑
尝试在这个相关的 SO 问题中使用答案:https ://stackoverflow.com/a/57025115/8645002没有解决问题。在 Linux 环境中运行构建的 exe 时,委托仍然不会触发。
注意:为 Linux x64 构建单文件自包含 exe。