如何检查与.NET,C#,WPF互联网连接 [英] How to check internet connection with .NET, C#, WPF
问题描述
我使用.NET,C#和WPF,我需要检查连接是否被打开到一定的网址,我不能得到任何code的工作,我发现在互联网上。
I am using .NET, C# and WPF and I need to check whether the connection is opened to a certain URL and I can't get any code to work that I have found on the 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服务器。
But i always get the message that everything is ok even if i shut down my local apache server.
我也试过:
ing ping = new Ping();
PingReply reply;
try
{
reply = ping.Send("localhost/myfolder/");
if (reply.Status != IPStatus.Success) MessageBox.Show("Internet is down!");
else MessageBox.Show("Seems OK");
}
catch (Exception ex)
{
MessageBox.Show("Error: "+ex.Message);
}
但是,这总是给一个例外(平似乎只有工作ping服务器,所以本地主机的作品,但本地主机/ MyFolder中/犯规)
But this always gives an exception (ping seems to work only pinging the server, so localhost works but localhost/myfolder/ doesnt)
请如何检查连接,所以它会为我工作?
Please how to check the connection so it would work for me?
推荐答案
在最后,我用我自己的code:
In the end I used my own code:
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)IM没有得到任何HTTP状态,但将引发异常。但这部作品不够好:)
An interesting thing is that when the server is down (i turn off my apache) i m not getting any http status but an exception is thrown. But this works good enough :)
这篇关于如何检查与.NET,C#,WPF互联网连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!