c# - FileSystemWatcher 中的 FileNotFoundException

标签 c# .net file exception file-watcher

我正在使用 FileSystemWatcher在目录上并添加其事件处理程序,设置其 EnableRaisingEvents=true;IncludeSubdirectories=false;并添加了 NotifyFilters .

在运行应用程序时,如果我有时在指定目录中创建新文件夹,我会得到

FileNotFoundException : "An error occurred while reading a directory". System.IO.FileSystemWatcher.StartRaisingEvents() System.IO.FileSystemWatcher.set_EnableRaisingEvents(Boolean value)

问题的根本原因是什么?

什么是 StartRaisingEvents()

最佳答案

只是出于愚蠢,我在思考之前用谷歌搜索了它。

在我的例子中,Path 是在之后 EnableRaisingEvents 定义的。

例如不会抛出异常:

FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"C:\";
//...
watcher.EnableRaisingEvents = true;

这将:

FileSystemWatcher watcher = new FileSystemWatcher();
watcher.EnableRaisingEvents = true;
//...
watcher.Path = @"C:\";

所以。因为我喜欢快速失败而不是让下一个人弄清楚到底发生了什么,所以我在路径声明之后修改了它:

var watcher = new FileSystemWatcher();
watcher.Path = @"C:\Users\me";
if (string.IsNullOrWhiteSpace(watcher.Path))
    throw new InvalidOperationException($"You must define a path.");
if (!Directory.Exists(watcher.Path))
    throw new InvalidOperationException($"Directory {watcher.Path} does not exist.");
watcher.EnableRaisingEvents = true;

愚蠢的问题,但至少我给出了一些古怪的快速失败解决方案。

关于c# - FileSystemWatcher 中的 FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3976862/

相关文章:

c# - 为什么我可以将不可为 null 的类型与 null 进行比较?

c# - 我的 ASP.NET DropDownList 无法正常工作

c# - ViewModel 和单例模式

c - 为什么这个程序的行为类似于 `tail -f`

JAVA 为什么只有图像才能与 class.getResource 配合使用

Java 在属性文件中查找具有特定值的键

c# - 修改从 ObjectDataSource 返回的集合

c# - 在 .NET 中,null 的哈希码是否应始终为零

c# - 如何在C#中剪切图像的一部分

c# - 将字符串数组从托管代码编码到 native 代码