我希望我的程序在C#中检查一个网站在执行之前是否在线,我如何让我的程序ping网站并检查C#中的响应?
答案 0 :(得分:50)
Ping仅告诉您端口处于活动状态,它不会告诉您它是否真的是一个Web服务。
我的建议是针对网址执行HTTP HEAD请求
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("your url");
request.AllowAutoRedirect = false; // find out if this site is up and don't follow a redirector
request.Method = "HEAD";
try {
response = request.GetResponse();
// do something with response.Headers to find out information about the request
} catch (WebException wex)
{
//set flag if there was a timeout or some other issues
}
这实际上不会获取HTML页面,但它会帮助您找出您需要知道的最低限度。对不起,如果代码没有编译,这只是我的头脑。
答案 1 :(得分:45)
您已使用System.Net.NetworkInformation.Ping
,请参阅下文。
var ping = new System.Net.NetworkInformation.Ping();
var result = ping.Send("www.google.com");
if (result.Status != System.Net.NetworkInformation.IPStatus.Success)
return;
答案 2 :(得分:20)
Digicoder代码的小注释和Ping方法的完整示例:
private bool Ping(string url)
{
try
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Timeout = 3000;
request.AllowAutoRedirect = false; // find out if this site is up and don't follow a redirector
request.Method = "HEAD";
using (var response = request.GetResponse())
{
return true;
}
}
catch
{
return false;
}
}
答案 3 :(得分:3)
if (!NetworkInterface.GetIsNetworkAvailable())
{
// Network does not available.
return;
}
Uri uri = new Uri("http://stackoverflow.com/any-uri");
Ping ping = new Ping();
PingReply pingReply = ping.Send(uri.Host);
if (pingReply.Status != IPStatus.Success)
{
// Website does not available.
return;
}
答案 4 :(得分:1)
我能想到的最简单的方法是:
WebClient webClient = new WebClient();
byte[] result = webClient.DownloadData("http://site.com/x.html");
如果网站不在线,DownloadData将抛出异常。
可能有一种类似的方式来ping网站,但除非你每秒多次检查,否则差异不大可能会显着。