38

何らかの理由で、私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));
    }
}
4

5 に答える 5

21

このセッターを使用して、トリガーを有効にします。

watcher.EnableRaisingEvents = true;
于 2017-03-01T10:14:06.137 に答える
0

私の問題は、サブディレクトリも監視することを期待していたが、デフォルトでは監視していないことでした。サブディレクトリも監視したい場合は、IncludeSubdirectories プロパティを true に設定します (デフォルトでは false です)。

fileSystemWatcher.IncludeSubdirectories = true;
于 2020-08-23T19:50:26.230 に答える
-2

フォルダーを移動しても予期したイベントがトリガーされないという、非常によく似た問題が発生しました。解決策は、単に移動するのではなく、フォルダー全体をハード コピーすることでした。

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
于 2016-08-23T08:57:28.147 に答える