C#:删除监视文件夹后 FileSystemWatcher 会发生什么

C#: What happens to the FileSystemWatcher after watched folder is deleted

我正在为我正在开发的一些代码使用 FileSystemWatchers。不过,我确实有一个问题,当 FSW 正在监视的文件夹被删除时会发生什么?

我的用例是这样的:

  1. 用户创建目录 Foo

  2. 然后我的代码使用和 FSW

  3. 观察 Foo
  4. 用户删除 Foo

  5. 稍后,用户重新创建 Foo 目录。

在这种情况下,原来的 FSW 会怎样?它仍然会监视新目录,还是我必须创建一个新目录?

非常感谢任何帮助。

MSDN 说:

Some common occurrences, such as copying or moving a file or directory, do not correspond directly to an event, but these occurrences do cause events to be raised. When you copy a file or directory, the system raises a Created event in the directory to which the file was copied, if that directory is being watched. If the directory from which you copied was being watched by another instance of FileSystemWatcher, no event would be raised. For example, you create two instances of FileSystemWatcher. FileSystemWatcher1 is set to watch "C:\My Documents", and FileSystemWatcher2 is set to watch "C:\Your Documents". If you copy a file from "My Documents" into "Your Documents", a Created event will be raised by FileSystemWatcher2, but no event is raised for FileSystemWatcher1. Unlike copying, moving a file or directory would raise two events. From the previous example, if you moved a file from "My Documents" to "Your Documents", a Created event would be raised by FileSystemWatcher2 and a Deleted event would be raised by FileSystemWatcher1.

TL;DR: 不,FSW 不会自动 观看 "Foo" 重建后。


验证它最简单的方法就是测试它,所以我做到了。

如果您使用 FileSystemWatcher 的实例监视目录 "Foo",然后删除正在监视的目录,则 FileSystemWatcher 将停止监视该目录。

即使在重新创建同名目录 "Foo" 之后,FileSystemWatcher 也不会再针对该目录中的任何更改引发事件。

删除并重新创建 "Foo" 后,尝试 "reset" FileSystemWatcher,方法是将其 Path 属性 设置为 "Foo" 和 EnableRaisingEvents 属性 到 true 不能始终如一地工作 - 它第一次工作正常,但如果 "Foo" 被删除并第二次重新创建则无法这样做。 (这在 Visual Studio 2017 社区版中进行了测试)。

遗憾的是,在这种情况下,使 FileSystemWatcher 按预期工作的唯一一致方法是创建 FileSystemWatcher 的新实例。