FileSystemWatcher没有触发事件

出于某种原因,我的FileSystemWatcher没有触发任何事件。 我想知道在我的目录中创建,删除或重命名新文件的任何时间。 _myFolderPath设置正确,我已经检查过了。

这是我目前的代码:

 public void Setup() { var fileSystemWatcher = new FileSystemWatcher(_myFolderPath); fileSystemWatcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; fileSystemWatcher.Changed += FileSystemWatcherChanged; fileSystemWatcher.Created += FileSystemWatcherChanged; fileSystemWatcher.Deleted += FileSystemWatcherChanged; fileSystemWatcher.Renamed += FileSystemWatcherChanged; fileSystemWatcher.Filter = "*.*"; fileSystemWatcher.EnableRaisingEvents = true; } private void FileSystemWatcherChanged(object sender, FileSystemEventArgs e) { MessageBox.Show("Queue changed"); listBoxQueuedForms.Items.Clear(); foreach (var fileInfo in Directory.GetFiles(_myFolderPath, "*.*", SearchOption.TopDirectoryOnly)) { listBoxQueuedForms.Items.Add(fileInfo)); } } 

您似乎在setup方法中将FileSystemWatcher创建为局部变量。 当然,这将在方法结束时超出范围,并且很可能在此时进行整理,从而移除手表。

尝试在持久化的位置创建FSW(例如程序级变量)并查看是否对您进行排序。

我的问题是我期望某些操作导致FileSystemWatcher Changed事件触发。 例如,将文件(单击并拖动)从桌面移动到监视位置不会引发事件,而是复制现有文件并粘贴其新副本(通过在文件系统中创建新文件而不是简单地移动现有的一个)引发了Changed事件。

我的解决方案是将每个NotifyFilter添加到我的FileSystemWatcher 。 这样我在FileSystemWatcher能够通知我的所有情况下都会收到通知。

请注意 ,对于特定情况,哪些filter会通知您,这并不完全直观/明显。 例如,我希望如果我包含FileName ,我将收到有关现有文件名称的任何更改的通知…而不是Attributes似乎处理这种情况。

 watcher.NotifyFilter = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Size | NotifyFilters.Security; 

使用此setter启用触发器:

 watcher.EnableRaisingEvents = true; 

我们遇到了一个非常类似的问题,即移动文件夹并未触发预期的事件。 解决方案是硬拷贝整个文件夹,而不是仅仅移动它。

 DirectoryCopy(".", ".\\temp", True) Private Shared Sub DirectoryCopy( _ ByVal sourceDirName As String, _ ByVal destDirName As String, _ ByVal copySubDirs As Boolean) ' Get the subdirectories for the specified directory. Dim dir As DirectoryInfo = New DirectoryInfo(sourceDirName) If Not dir.Exists Then Throw New DirectoryNotFoundException( _ "Source directory does not exist or could not be found: " _ + sourceDirName) End If Dim dirs As DirectoryInfo() = dir.GetDirectories() ' If the destination directory doesn't exist, create it. If Not Directory.Exists(destDirName) Then Directory.CreateDirectory(destDirName) End If ' Get the files in the directory and copy them to the new location. Dim files As FileInfo() = dir.GetFiles() For Each file In files Dim temppath As String = Path.Combine(destDirName, file.Name) file.CopyTo(temppath, False) Next file ' If copying subdirectories, copy them and their contents to new location. If copySubDirs Then For Each subdir In dirs Dim temppath As String = Path.Combine(destDirName, subdir.Name) DirectoryCopy(subdir.FullName, temppath, true) Next subdir End If End Sub