【问题标题】:Create multiple FileSystemWatcher instances dynamically动态创建多个 FileSystemWatcher 实例
【发布时间】:2016-02-17 15:22:45
【问题描述】:

我有一个从这里找到的示例编写的文件系统观察器,它工作正常,大致如下:

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

【问题讨论】:

  • 您正在努力解决哪个特定部分。这不是翻译服务。唯一的主要语法差异是 fsw.Created += file_OnCreated; 应该使用 AddHandler fsw.Created, file_OnCreated 等。
  • 对不起@MattWilko - 这不是我正在努力解决的处理程序,而是从一组文件夹中动态创建多个 FileSystemWatchers。从可能在运行时定义的未知数量的路径中监视多条路径。我正在寻找如何监视多个路径的 VB.NET 示例,而不是如何添加处理程序。我有用于监视单个文件夹的工作代码,或者如果我有已知固定数量的文件夹,则可以用于多个文件夹,这是从我正在努力解决的数组或其他路径列表中动态创建多个监视器
  • 您需要展示您的尝试并具体说明您遇到的问题,以便有人帮助您。没有任何代码,任何人都可以为您翻译整个答案,您可以使用免费的在线转换器自己完成
  • @plutonix 谢谢,但这并没有解决创建(直到运行时)未知数量的监控路径。不过还是有用的。

标签: .net vb.net filesystemwatcher c#-to-vb.net


【解决方案1】:

在 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

【讨论】:

  • 遗憾的是,这对其他访问者来说不是一个有用的答案,所以我投票结束这个问题。
  • @MattWilko ??这对我很有用。我在任何地方都找不到其他示例,说明如何在任何地方的 VB.NET 中动态添加多个文件观察程序,这是对此的答案。像我这样的其他人使用这个网站来寻找例子,这是一个。
  • 但是问题的本质是关于在运行时添加多个对象,其中有很多例子。
猜你喜欢
  • 2016-04-01
  • 1970-01-01
  • 2011-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-11
  • 2015-12-17
  • 1970-01-01
相关资源
最近更新 更多