【问题标题】:Watch Folder in VB.net/WPFVB.net/WPF 中的监视文件夹
【发布时间】:2012-01-22 12:38:22
【问题描述】:

我在尝试找出如何监视文件夹以进行更改时遇到问题。这是我已经走了多远:

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

问题是当文件夹中发生更改时,程序退出时没有错误代码。我已经阅读了一些相关的帖子,我知道这与线程安全有关。但是我不知道如何使这个程序“线程安全”。谁能给我一些建议?谢谢!

【问题讨论】:

  • 因什么而崩溃?空引用?
  • 不,抱歉,它没有“崩溃”,程序只是退出,没有错误消息
  • 为帮助将来捕获此类错误,请在 Visual Studio 的调试菜单下的“异常...”窗口中的“公共语言运行时异常”上设置“抛出异常时中断”。

标签: vb.net filesystemwatcher


【解决方案1】:

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

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

应该是

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

【讨论】:

  • 显然这只会影响重命名。如果这不能解决问题,请说明您对临时目录中的文件执行的操作,以防对问题产生一些影响。
  • 嘿,感谢您的更改,现在无需退出重命名即可使用!我不敢相信我忽略了这一点。此外,我只测试了我检查过的代码的重命名功能,其他处理程序正在工作。
猜你喜欢
  • 1970-01-01
  • 2019-03-09
  • 2021-08-08
  • 1970-01-01
  • 2022-01-01
  • 2012-10-05
  • 2019-07-02
  • 1970-01-01
相关资源
最近更新 更多