我有一个从这里找到的示例编写的filesystemwatcher,工作正常,符合以下几行:
Public monitor As FileSystemWatcher
monitor = New System.IO.FileSystemWatcher()
monitor.Path = c:\temp\
monitor.NotifyFilter = IO.NotifyFilters.DirectoryName
monitor.NotifyFilter = monitor.NotifyFilter Or IO.NotifyFilters.FileName
monitor.NotifyFilter = monitor.NotifyFilter Or IO.NotifyFilters.Attributes
'Add handlers
AddHandler monitor.Changed, AddressOf fileevent
AddHandler monitor.Created, AddressOf fileevent
AddHandler monitor.Deleted, AddressOf fileevent
'Start watching
monitor.EnableRaisingEvents = True
我正在努力解决的问题是扩展这个以监控多个文件夹,但不知道除了在运行时有多少文件夹需要监控。
这个问题似乎在C#中涵盖了它 Multiple Configurable FileSystemWatcher methods
但是我缺乏经验到目前为止阻止我无法将其转换为VB.NET
答案 0 :(得分:0)
随着Matt Wilko的提示让我疲惫的大脑更加紧张,我找到了解决方案,谢谢。
Private fsWatchers As New List(Of FileSystemWatcher)()
Public Sub AddWatcher(wPath As String)
Dim fsw As New FileSystemWatcher()
fsw.Path = wPath
AddHandler fsw.Created, AddressOf logchange
AddHandler fsw.Changed, AddressOf logchange
AddHandler fsw.Deleted, AddressOf logchange
fsWatchers.Add(fsw)
End Sub
使用类似于:
的处理程序Public Sub logchange(ByVal source As Object, ByVal e As System.IO.FileSystemEventArgs)
'Handle change, delete and new events
If e.ChangeType = IO.WatcherChangeTypes.Changed Then
WriteToLog("File " & e.FullPath.ToString & " has been modified")
End If
If e.ChangeType = IO.WatcherChangeTypes.Created Then
WriteToLog("File " & e.FullPath.ToString & " has been created")
End If
If e.ChangeType = IO.WatcherChangeTypes.Deleted Then
WriteToLog("File " & e.FullPath.ToString & " has been deleted")
End If
End Sub
然后使用每个路径调用AddWatcher(根据您的需要从数组,XML文件或表单列表中),当您添加所有路径时设置过滤器并开始监控:
For Each fsw In fsWatchers
fsw.NotifyFilter = IO.NotifyFilters.DirectoryName
fsw.NotifyFilter = watchfolder.NotifyFilter Or IO.NotifyFilters.FileName
fsw.NotifyFilter = watchfolder.NotifyFilter Or IO.NotifyFilters.Attributes
fsw.EnableRaisingEvents = True
Next