如何检查与.NET,C#和WPF的Internet连接
我正在使用.NET,C#和WPF,我需要检查连接是否打开到某个URL,我无法获得任何我在Internet上找到的代码。
我试过了:
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { IAsyncResult result = socket.BeginConnect("localhost/myfolder/", 80, null, null); bool success = result.AsyncWaitHandle.WaitOne(3000, true); if (!success) { MessageBox.Show("Web Service is down!"); } else MessageBox.Show("Everything seems ok"); } finally { socket.Close(); }
但即使我关闭了我的本地Apache服务器,我也总是得到一切正常的信息。
我也尝试过:
ing ping = new Ping(); PingReply reply; try { reply = ping.Send("localhost/myfolder/"); if (reply.Status != IPStatus.Success) MessageBox.Show("The Internet connection is down!"); else MessageBox.Show("Seems OK"); } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); }
但这总是给出一个例外(ping似乎只能ping服务器,所以localhost工作但localhost / myfolder / doesnt)
请问如何检查连接,以便它对我有用?
许多开发人员只是通过ping Google.com来解决这个“问题”。 好…? :/这适用于大多数(99%)的情况,但专业是如何依赖您的应用程序在某些外部Web服务上的工作?
有一个非常有趣的Windows API函数
InternetGetConnectedState()
可以识别您是否可以访问Internet,而不是ping Google.com。
这种情况的解决方案是:
using System; using System.Runtime; using System.Runtime.InteropServices; public class InternetAvailability { [DllImport("wininet.dll")] private extern static bool InternetGetConnectedState(out int description, int reservedValue); public static bool IsInternetAvailable( ) { int description; return InternetGetConnectedState(out description, 0); } }
最后我使用了自己的代码:
private bool CheckConnection(String URL) { try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); request.Timeout = 5000; request.Credentials = CredentialCache.DefaultNetworkCredentials; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode == HttpStatusCode.OK) return true; else return false; } catch { return false; } }
一个有趣的事情是,当服务器关闭时(我关闭我的Apache)我没有获得任何HTTP状态,但抛出exception。 但这足够好:)
用这个:
private bool CheckConnection() { WebClient client = new WebClient(); try { using (client.OpenRead("https://www.google.com")) { } return true; } catch (WebException) { return false; } }
你可以试试这个;
private bool CheckNet() { bool stats; if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() == true) { stats = true; } else { stats = false; } return stats; }
我认为这在Windows应用程序,Windows窗体或WPF应用程序中更准确,而不是使用WebClient或HttpWebRequest,
public class InternetChecker { [System.Runtime.InteropServices.DllImport("wininet.dll")] private extern static bool InternetGetConnectedState(out int Description, int ReservedValue); //Creating a function that uses the API function... public static bool IsConnectedToInternet() { int Desc; return InternetGetConnectedState(out Desc, 0); } }
在打电话时写
上述就是C#学习教程:如何检查与.NET,C#和WPF的Internet连接分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
if(InternetCheckerCustom.CheckNet()) { // Do Work } else { // Show Error MeassgeBox }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/982979.html