1

干杯! 我正在使用 .net 4.0 并编写一个 vb.net 控制台应用程序。应用程序必须监视文件夹并在每次将新文件保存到其中时执行某些操作

它总是第一次运行,但随后的运行似乎失败了,我不知道为什么。为了测试它,我在一个测试文件夹中有一堆测试图像,我一次将超过 1 个复制到捕获文件夹,等待它处理,然后尝试将另一个图像放在那里。

代码如下:

Public Sub FileChanges()
      Dim result As System.IO.WaitForChangedResult
      watchfolder = New System.IO.FileSystemWatcher()
      watchfolder.Path = My.Settings.WATCHDIR.ToString()
      Console.WriteLine("Application Running, Waiting for a file")
      result = watchfolder.WaitForChanged(System.IO.WatcherChangeTypes.Created)
      Console.WriteLine("Filechange Detected")
      Dim fileName As String = My.Settings.WATCHDIR.ToString() & result.Name.ToString()
End Sub
sub main()
   Do
     system.threading.thread.sleep(5000)
     FileChanges()
   Loop
End Sub

有什么想法吗?控制台应用程序中的任何更好的方法可以等到创建文件然后执行某些操作?

4

1 回答 1

1

Declare the watcher only once, and enable raising events:

watchfolder.EnableRaisingEvents = True

Then use a handler to handle the change event:

Private Sub watchfolder_event(ByVal sender As Object, _
ByVal e As system.IO.FileSystemEventArgs) Handles watchfolder.changed
...

Here's an example that works in VB 2008:

Module Module1

Dim WithEvents watchfolder As New System.IO.FileSystemWatcher

Sub Main()
watchfolder.Path = "c:\tmp"
watchfolder.EnableRaisingEvents = True

For i As Integer = 1 To 500
  System.Threading.Thread.Sleep(1000)
  Console.WriteLine("tick " & i)
Next i

End Sub

Private Sub watchfolder_event(ByVal sender As Object, ByVal e As System.IO.FileSystemEventArgs) Handles watchfolder.Changed
Console.WriteLine("changed.")
End Sub

End Module
于 2013-09-05T23:54:55.670 回答