我正在使用.NET,C#和WPF,我需要检查连接是否打开到某个网址,我无法获得任何我在互联网上找到的代码。
我试过了:
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/不能)
请告诉我如何检查连接才能为我工作?
发布于 2011-03-23 22:37:57
最后,我使用了自己的代码:
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状态,但是会抛出一个异常。但这已经足够好用了:)
发布于 2013-06-27 14:02:06
你可以试试这个;
private bool CheckNet()
{
bool stats;
if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() == true)
{
stats = true;
}
else
{
stats = false;
}
return stats;
}
发布于 2011-03-23 21:51:37
使用以下命令:
private bool CheckConnection()
{
WebClient client = new WebClient();
try
{
using (client.OpenRead("http://www.google.com"))
{
}
return true;
}
catch (WebException)
{
return false;
}
}
https://stackoverflow.com/questions/5405895
复制相似问题