我正在尝试从网页中获取结果,并且为了避免web异常,我想在从流中请求结果之前检查状态代码。但是:
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();当我尝试在此之后使用response.StatusCode获取错误代码时引发异常
有没有一种方法可以避免异常来获取StatusCode
发布于 2012-10-25 16:59:26
只有在调用了GetResponse()方法之后,才能请求StatusCode。您需要将GetResponse()包装在try/catch块中。看看Check if a url is reachable - Help in optimizing a Class吧。
如果你只是想测试服务器的可达性,那么你可以使用Ping命令。
发布于 2012-10-25 17:02:50
您可以使用Ping从该站点获取更多统计数据。(虽然有点慢,但需要1-3秒左右)
public string ExecuteCommandSync(object command)
{
try
{
// create the ProcessStartInfo using "cmd" as the program to be run,
// and "/c " as the parameters.
// Incidentally, /c tells cmd that we want it to execute the command that follows,
// and then exit.
var procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
// The following commands are needed to redirect the standard output.
// This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
var proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
return proc.StandardOutput.ReadToEnd();
}
catch (Exception objException)
{
Console.WriteLine("Error: " + objException.Message);
return "";
// Log the exception
}
}[发自:C# cmd output in real time Just From changed ]
用法如下:
MessageBox.Show(ExecuteCommandSync("ping www.stackoverflow.com"));https://stackoverflow.com/questions/13064943
复制相似问题