如何检测DownloadString是否失败?

时间:2017-12-03 05:40:55

标签: vb.net ip try-catch detection downloadstring

我尝试将外部IP放入标签中,因此我根据网站下载结果,但是当我通过VPN更改IP时,应用程序崩溃,我相信&# 39;因为它没有检查它是否正在关闭字符串,他试过了。

表格加载......

 If Label1.Text = LastIp Then

      Try

      Dim wc As New WebClient
      Label1.Text = wc.DownloadString("http://icanhazip.com/")

      If you can not then

      Label.Text = "Failed to get IP"

      End if

 End If

表单...

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以设置回调并指定文件的路径:

Dim wc As New WebClient
AddHandler wc.DownloadStringCompleted, AddressOf DownloadStringComplete
wc.DownloadStringAsync(New Uri("http://icanhazip.com/myfile.txt", UriKind.Absolute))

Private Sub DownloadStringComplete(ByVal sender As Object, ByVal e As DownloadStringCompletedEventArgs)

If Not IsNothing(e.Error) Then
    Label1.Text = e.Error.Message
ElseIf e.Cancelled Then
    Label1.Text = "canceled"
Else
    Label1.Text = e.Result
End If

End Sub