只是出于愚蠢,我在思考之前搜索了它。
就我而言,路径是在EnableRaisingEvents之后定义的。
eg不会抛出异常:
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;
愚蠢的问题,但至少我给出了一些古怪的快速失败解决方案。