vb.net – 检查Internet连接
发布时间:2020-12-17 07:24:42 所属栏目:百科 来源:网络整理
导读:我需要我的应用程序来检查用户计算机上的互联网连接.如果有,则显示图像,如果没有,则显示不同的图像.这是我用来实现这个的代码: Private Sub Window_Loaded(ByVal sender As System.Object,ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loade
我需要我的应用程序来检查用户计算机上的互联网连接.如果有,则显示图像,如果没有,则显示不同的图像.这是我用来实现这个的代码:
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("Imagesgreenbar.png",UriKind.Relative) bi1.EndInit() Image2.Source = bi1 Else Dim bi2 As New BitmapImage bi2.BeginInit() bi2.UriSource = New Uri("Imagesredbar.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连接.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |