.net 动态创建多个FileSystemWatcher实例

.net 动态创建多个FileSystemWatcher实例,.net,vb.net,filesystemwatcher,c#-to-vb.net,.net,Vb.net,Filesystemwatcher,C# To Vb.net,我有一个filesystemwatcher,它是根据这里的示例编写的,运行良好,大致如下: Public monitor As FileSystemWatcher monitor = New System.IO.FileSystemWatcher() monitor.Path = c:\temp\ monitor.NotifyFilter = IO.NotifyFilters.DirectoryName monitor.NotifyFilter = monitor.NotifyFilter Or

我有一个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来回答#


但由于我缺乏经验,目前为止我无法将其翻译成VB.NET,马特·威尔科提醒我将我疲惫的大脑再推进一点,我找到了一个解决方案,谢谢

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
然后使用每个要监视的路径(根据需要从数组、XML文件或表单列表)调用AddWatcher,并在添加所有路径后设置过滤器并开始监视:

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

你在为哪一部分而挣扎。这不是翻译服务。唯一主要的语法差异是
fsw.Created+=file\u OnCreated
应该使用
AddHandler fsw.Created,file\u OnCreated
等。可以从tooSorry@MattWilko的问题中学习-我要解决的不是处理程序,而是从一系列文件夹中动态创建多个FileSystemWatcher。从运行时可能定义的未知数量的路径监视多个路径。我正在寻找一个VB.NET示例,说明如何监视多个路径,而不是如何添加处理程序。我有用于监视单个文件夹的工作代码,如果我有已知固定数量的文件夹,则有用于监视多个文件夹的工作代码,这是从阵列或其他路径列表中动态创建多个监视器的过程,我正在努力解决这一问题。您需要展示您的尝试,并具体解释您遇到的问题,以便有人帮助您。没有任何代码,任何人都可以为你翻译整个答案,你可以自己做一个免费的在线翻译converter@plutonix谢谢,但这并不能解决创建(直到运行时)未知数量的要监视的路径的问题。但仍然很有用。遗憾的是,对于其他来访者来说,这不是一个有用的答案,所以我投票决定结束这个问题。@MattWilko??这对我会有用的。在VB.NET anywhere中,我还没有找到其他关于如何动态添加多个文件查看器的示例,这就是答案。像我这样的其他人使用这个网站寻找例子,这是一个。但问题的实质是在运行时添加多个对象,其中有很多例子。