PhysicalFilesWatcher 验证根目录和 FileSystemWatcher 路径

PhysicalFilesWatcher 构造函数现在会验证 root 参数以及 root 和 FileSystemWatcher.Path 之间的关系。 以前在构造期间可被接受的无效组合现在会抛出异常。

引入的版本

.NET 11 预览版 4

以前的行为

此前,PhysicalFilesWatcher 构造函数在未进行验证或规范化的情况下存储了传入的 root。 null 或其他无效的根可能会在构造时被接受,但在后续的监视器操作中失败。

构造函数也接受其非空 Path 与 root 无关的 FileSystemWatcher。 这类监视器通常无法报告与已配置根目录相关的更改,但这种不匹配并不会导致构造函数抛出异常。

例如,以下构造方式成功了:

string root = Path.Combine(Path.GetTempPath(), "root");
string unrelatedPath = Path.Combine(Path.GetTempPath(), "unrelated");
Directory.CreateDirectory(root);
Directory.CreateDirectory(unrelatedPath);

using var fileSystemWatcher = new FileSystemWatcher(unrelatedPath);
using var watcher = new PhysicalFilesWatcher(
    root,
    fileSystemWatcher,
    pollForChanges: false);

新行为

从 .NET 11 开始,PhysicalFilesWatcher构造函数通过在构造时调用Path.GetFullPath()和拒绝无效输入来规范化root:

  • 如果 null 是 root,构造函数会抛出 ArgumentNullException。
  • 如果 root 无法转换为完整路径,构造函数将从 Path.GetFullPath()中传播适用的异常。
  • 如果 FileSystemWatcher.Path 为非空且与 root 无关,则构造函数会抛出 ArgumentException。

FileSystemWatcher.Path 在其为空、等于 root、是 root 的祖先或是 root 的后代时有效。 在前面的示例中,构造过程现在会抛出 ArgumentException,因为 unrelatedPath 既不是 root 的祖先,也不是其后代。

尚不存在的根目录仍然有效。 文件监视将推迟到根目录创建之后。

破坏性变更的类型

此更改为行为更改。

更改原因

PhysicalFilesWatcher 现在支持构造观察程序时不存在的根。 这需要对该根进行规范化,并使所提供的 FileSystemWatcher 与该根相协调。

监视无关目录的FileSystemWatcher无法可靠地针对已配置的根目录发出通知。 在构造阶段拒绝这种无效组合,可以防止在通常无法正常工作的配置下创建监视器。 对根路径的验证还会使无效路径立即报错,而不是等到后续的监视器操作时才报错。 有关详细信息,请参阅 dotnet/runtime#126411。

将非空且有效的路径作为 root 传递。

当你为 FileSystemWatcher 提供非空的 Path 时,请将其路径配置为与 root 相同、为 root 的祖先目录,或为 root 的子目录。 例如:

string root = Path.GetFullPath(configuredRoot);

using var fileSystemWatcher = new FileSystemWatcher(root);
using var watcher = new PhysicalFilesWatcher(
    root,
    fileSystemWatcher,
    pollForChanges: false);

如果根目录尚不存在,则空 FileSystemWatcher.Path 目录有效:

string root = Path.GetFullPath(configuredRoot);

using var fileSystemWatcher = new FileSystemWatcher();
using var watcher = new PhysicalFilesWatcher(
    root,
    fileSystemWatcher,
    pollForChanges: false);

观察程序在创建根目录后开始监视。

受影响的 API