【问题标题】:How to detect if DownloadString Failed?如何检测 DownloadString 是否失败?
【发布时间】:2017-12-03 23:22:48
【问题描述】:

我正在尝试将我的外部 IP 放入标签中,因此我正在根据站点下载结果,但是当我通过 VPN 更改我的 IP 时,应用程序崩溃了,我相信这是因为它没有检查如果它把绳子拉下来,他试过了。

在表单加载中...

 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

表格...

【问题讨论】:

  • 使用Try/Catch statement。另外,如果您能告诉我们您遇到的错误,那将会很有帮助。

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


【解决方案1】:

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

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

【讨论】:

  • 没有文件,只有网站。
  • 如果您只想要默认页面,只需使用不带文件名的“icanhazip.com”,或者最好指定页面名称,例如:“icanhazip.com/default.html”。如果您想下载另一个主题的整个网站。
  • 不要使用If Not IsNothing(e.Error) Then,那是VB6风格的代码。请改用If e.Error IsNot Nothing Then。
猜你喜欢
  • 2013-08-26
  • 2016-08-08
  • 1970-01-01
  • 1970-01-01
  • 2018-07-06
  • 2013-08-30
  • 1970-01-01
  • 2018-12-05
  • 2015-12-17
相关资源
最近更新 更多