c# - 如果 FileSystemWatcher 与应用程序位于同一驱动器上,则 FileSystemWatcher 无法使用设置为驱动器根目录的路径

标签 c# .net path filesystemwatcher

我正在使用 FileSystemWatcher 检查对驱动器上任何位置的 .exe 文件的更改。

FileSystemWatcher Watcher;

[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public void Start() {
    Watcher = new FileSystemWatcher("C:") {
        NotifyFilter = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Size | NotifyFilters.Security,
        Filter = "*.exe",
        IncludeSubdirectories = true
    };
    Watcher.Created += OnChanged; //Among other events
    Watcher.EnableRaisingEvents = true;
}

private void OnChanged(object source, FileSystemEventArgs e) {
    Debug.WriteLine(e.FullPath);
}

问题是,如果我将观察者的路径设置为 C: 以检查整个 C: 驱动器上的文件,同时让我的应用程序在任何地方运行C: 驱动器(例如 C:\Users\Name\Desktop\App.exe),观察程序不会触发任何事件。

如果我改为将路径设置为 C:\Users 那么观察者将触发事件 - 但这当然仅限于对 C:\Users 下的文件所做的更改> 如果文件位于 Program Files 或类似文件中,这将无济于事。

当我的应用程序位于 D: 驱动器上的任何位置时,如果我让 watcher 检查 D: 驱动器,则会发生同样的问题。

因此,似乎无法将路径设置为运行应用程序的驱动器的根目录。可能是什么原因造成的?

最佳答案

您需要将 @"C:\" 传递给构造函数而不是 "C:"

路径 C: 表示“C: 驱动器上的当前目录”,而 C:\ 表示“根目录C: 驱动器。”您可以通过打开 命令提示符 并运行...

来亲自查看
cd /D "%SystemRoot%"
dir %SystemDrive%\
dir %SystemDrive%

第二个命令(例如dir C:\)将显示系统驱动器根目录的内容,而最后一个命令(例如dir C:)将显示系统驱动器上当前目录的内容,即系统目录(例如C:\Windows)。那是因为它是一个相对 路径,但针对特定的驱动器。来自 Naming Files, Paths, and Namespaces ...

If a file name begins with only a disk designator but not the backslash after the colon, it is interpreted as a relative path to the current directory on the drive with the specified letter. Note that the current directory may or may not be the root directory depending on what it was set to during the most recent "change directory" operation on that disk. Examples of this format are as follows:

  • "C:tmp.txt" refers to a file named "tmp.txt" in the current directory on drive C.
  • "C:tempdir\tmp.txt" refers to a file in a subdirectory to the current directory on drive C.

假设当您启动 C:\Users\Name\Desktop\App.exe 时,它有一个工作目录 C:\Users\Name\Desktop\,通过将 "C:" 传递给 FileSystemWatcher 它最终只监视 C:\Users\Name\Desktop\ 目录,而不是整个卷像你要的那样。我在一个快速的 .NET Core 应用程序中测试了您的代码,并确认在传递 "C:" 时仅报告在当前(应用程序)目录中所做的更改,而在传递 @"C:\" 它确实正确地监控了整个卷。

关于c# - 如果 FileSystemWatcher 与应用程序位于同一驱动器上,则 FileSystemWatcher 无法使用设置为驱动器根目录的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60331451/

相关文章:

c# - 如何使用提供的凭据调用 SSPI 的 'AcquireCredentialsHandle'?

c# - 使用 WPF C# 中的多个控件组合创建自定义控件

c# - 如何使用 C# 可靠地检查是否启用了 Windows 更新?

c# - 将 HttpListener 用于生产口径的 Web 服务器?

javascript - 比较客户端和服务器系统时间的差异(Javascript 和 C#)

c# - 如何为 N 单元测试使用多个 TestCaseSource 属性

python - 如何添加默认路径以在其中查找 python 脚本文件?

c# - ASP.NET Web 应用程序文件路径(在 Azure 上发布)

检查程序的不同目录

c# - .NET 中的标准输入和输出