VB.net/WPF中的监视文件夹



我在试图找出如何监视文件夹的更改时遇到了问题。这就是我的成就:

Class MainWindow
<PermissionSet(SecurityAction.Demand, Name:="FullTrust")> _
Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
    Dim Path As String = "C:Temp"
    ' Create a new FileSystemWatcher and set its properties.
    Dim watcher As New FileSystemWatcher()
    watcher.Path = Path
    ' Watch for changes in LastAccess and LastWrite times, and
    ' the renaming of files or directories. 
    watcher.NotifyFilter = (NotifyFilters.LastAccess Or NotifyFilters.LastWrite Or NotifyFilters.FileName Or NotifyFilters.DirectoryName)
    ' Only watch text files.
    watcher.Filter = "*.txt"
    ' Add event handlers.
    AddHandler watcher.Changed, AddressOf OnChanged
    AddHandler watcher.Created, AddressOf OnChanged
    AddHandler watcher.Deleted, AddressOf OnChanged
    AddHandler watcher.Renamed, AddressOf OnRenamed
    ' Begin watching.
    watcher.EnableRaisingEvents = True
End Sub
' Define the event handlers.
Private Shared Sub OnChanged(ByVal source As Object, ByVal e As FileSystemEventArgs)
    ' Specify what is done when a file is changed, created, or deleted.
    MsgBox("File: " & e.FullPath & " " & e.ChangeType)
End Sub
Private Shared Sub OnRenamed(ByVal source As Object, ByVal e As RenamedEventArgs)
    ' Specify what is done when a file is renamed.
    MsgBox("File: {0} renamed to {1}", e.OldFullPath, e.FullPath)
End Sub
End Class

问题是,当文件夹中发生更改时,程序将退出,而不会出现错误代码。我读过一些相关的帖子,我知道这与线程安全有关。然而,我不知道如何使这个程序"线程安全"。有人能给我一些建议吗?谢谢

我在这里没有遇到任何线程安全问题。我认为问题是:

MsgBox("File: {0} renamed to {1}", e.OldFullPath, e.FullPath)

应该是

MsgBox(String.Format("File: {0} renamed to {1}", e.OldFullPath, e.FullPath))

最新更新