我正在使用 FileSystemWatcher
在目录上并添加其事件处理程序,设置其 EnableRaisingEvents=true;
和 IncludeSubdirectories=false;
并添加了 NotifyFilters
.
在运行应用程序时,如果我有时在指定目录中创建新文件夹,我会得到 p>
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/