C# FileSystemWatcher 不触发事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16278783/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:36:40  来源:igfitidea点击:

FileSystemWatcher not firing events

c#filesystemwatcher

提问by gwin003

For some reason, my FileSystemWatcheris not firing any events whatsoever. I want to know any time a new file is created, deleted or renamed in my directory. _myFolderPathis being set correctly, I have checked.

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

Here is my current code:

这是我当前的代码:

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));
    }
}

采纳答案by Chris

You seem to be creating the FileSystemWatcher as a local variable in the setup method. This will of course go out of scope at the end of the method and may well be getting tidied up at that point, thus removing the watches.

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

Try creating the FSW at a point where it will be persisted (eg a program level variable) and see if that sorts you out.

尝试在将被持久化的点(例如程序级变量)创建 FSW,看看是否可以解决问题。

回答by MoMo

My problem was that I expected certain actions to cause the FileSystemWatcherChangedevent to fire. For example, moving a file (clicking and dragging) from the desktop to the watched location did not raise an event but copying an existing file and pasting a new copy of it (there by creating a new file to the file system and not simply moving an existing one) caused the Changedevent to be raised.

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

My solution was to add every NotifyFilterto my FileSystemWatcher. This way I am notified in all cases where the FileSystemWatcheris able to notify me.

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

NOTEthat it isn't entirely intuitive/obvious as to which filters will notify you for specific cases. For example, I expected that if I included FileNamethat I would be notified of any changes to an existing file's name...instead Attributesseem to handle that case.

请注意,对于特定情况,哪些过滤器会通知您并不完全直观/显而易见。例如,我希望如果我包含FileName了现有文件名的任何更改,我会收到通知......而不是Attributes似乎可以处理这种情况。

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

回答by Jonas_Hess

We just had a very similar problem, where moving a folder did not trigger the expected events. The solution was to hard copy the entire folder, rather than just moving it.

我们刚刚遇到了一个非常相似的问题,移动文件夹没有触发预期的事件。解决方案是硬复制整个文件夹,而不仅仅是移动它。

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

回答by Luca Ziegler

Use this setter to enable the trigger:

使用此设置器启用触发器:

watcher.EnableRaisingEvents = true;