0
这是一个新手问题。在同一个循环中读取文件+下载网页?
在循环中,我需要从文本文件中读取URL列表,下载网页并使用正则表达式搜索一些文本。
我用下面的代码,用DownloadStringAsync(),以避免冻结用户界面,但它触发的错误“Web客户端不支持并发I/O操作。”:
Private Sub AlertStringDownloaded(ByVal sender As Object, ByVal e As DownloadStringCompletedEventArgs)
If e.Cancelled = False AndAlso e.Error Is Nothing Then
Dim Content As String
Content = CStr(e.Result)
'Here, use regex to extract token
End If
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Read URLs from txt file
Dim FILE_NAME As String = "sites.txt"
Dim webClient As New WebClient
webClient.Encoding = System.Text.Encoding.UTF8
AddHandler webClient.DownloadStringCompleted, AddressOf AlertStringDownloaded
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objReader As New System.IO.StreamReader(FILE_NAME)
Do While objReader.Peek() <> -1
Line = objReader.ReadLine
'"WebClient does not support concurrent I/O operations."
webClient.DownloadStringAsync(New Uri(Line))
'Go to AlertStringDownloaded
Loop
Else
MsgBox("File Does Not Exist")
End If
End Sub
是否有人知道的替代?
谢谢。
编辑:显然,解决方案是强制应用程序暂停,直到当前页面被下载。有没有比使用DoEvents更好的方法?
Dim Busy As Boolean = False
Private Sub AlertStringDownloaded(ByVal sender As Object, ByVal e As DownloadStringCompletedEventArgs)
If e.Cancelled = False AndAlso e.Error Is Nothing Then
...
Busy = False
End If
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
...
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objReader As New System.IO.StreamReader(FILE_NAME)
Do While objReader.Peek() <> -1
...
'"WebClient does not support concurrent I/O operations."
Busy = True
webClient.DownloadStringAsync(New Uri(Line))
'Better way to pause until done downloading current page?
Do While Busy
System.Windows.Forms.Application.DoEvents()
Loop
Loop
Else
MsgBox("File Does Not Exist")
End If
End Sub
感谢您的链接。 – Gulbahar