微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

vb.net – 检查Internet连接

我需要我的应用程序来检查用户计算机上的互联网连接.如果有,则显示图像,如果没有,则显示不同的图像.这是我用来实现这个的代码

Private Sub Window_Loaded(ByVal sender As System.Object,ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded

    If networkinformation.NetworkInterface.GetIsNetworkAvailable Then
        Dim bi1 As New BitmapImage
        bi1.BeginInit()
        bi1.UriSource = New Uri("Images\greenbar.png",UriKind.Relative)
        bi1.EndInit()
        Image2.source = bi1

    Else
        Dim bi2 As New BitmapImage
        bi2.BeginInit()
        bi2.UriSource = New Uri("Images\redbar.png",UriKind.Relative)
        bi2.EndInit()
        Image2.source = bi2
        MessageBox.Show("INTERNET CONNECTION NOT DETECTED")
        MessageBox.Show("You must be connected to the internet to use some aspects of this application.")
        MessageBox.Show("Please re-establish connection to the Internet and try again,thank you.")
        Me.Close()

    End If
End Sub

我决定通过更改我的认网关在我自己的计算机上测试它(从而使它看起来好像我失去了连接).但我意识到代码显示我已连接.所以我认为它只是检查接口的连接 – 在这种情况下,是我与路由器的连接(这是真的,我连接到路由器).

所以,问题是:如何检查用户的PC是否实际连接到互联网?我阅读了文章What is the best way to check for Internet connectivity using .NET?,但它是在C#中,我不明白.

解决方法

您可以使用 this tool将C#转换为VB.NET,反之亦然:

Public Shared Function CheckForInternetConnection() As Boolean
    Try
        Using client = New WebClient()
            Using stream = client.OpenRead("http://www.google.com")
                Return True
            End Using
        End Using
    Catch
        Return False
    End Try
End Function

顺便说一下,您使用的NetworkInterface.GetIsNetworkAvailable方法检查是否有任何网络连接可用 – 而不是Internet连接.

A network connection is considered to be available if any network interface is marked “up” and is not a loopback or tunnel interface.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐