Skip to main content
 首页 » 编程设计

c#之FileSystemWatcher 中的 FileNotFoundException

2024年02月24日19qq号

我正在使用 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; 

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