Web ページから結果を取得しようとしていますが、Web 例外を回避するために、ストリームから結果を要求する前にステータス コードを確認したいと考えています。でも:
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
これを使用してエラーコードを取得しようとすると、例外がスローされます
response.StatusCode
を取得する例外を回避する方法はありStatusCode
ますか?
Web ページから結果を取得しようとしていますが、Web 例外を回避するために、ストリームから結果を要求する前にステータス コードを確認したいと考えています。でも:
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
これを使用してエラーコードを取得しようとすると、例外がスローされます
response.StatusCode
を取得する例外を回避する方法はありStatusCode
ますか?
GetResponse() メソッドを呼び出した後でのみ、StatusCode を要求できます。GetResponse() を try/catch ブロックでラップする必要があります。Check if a url is reachable - Help inoptimizing a Class をご覧ください。
サーバーの到達可能性をテストするだけの場合は、Ping を使用できます。
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
}
}
[From: C# cmd 出力をリアルタイム で少しだけ変更]
次のような使い方:
MessageBox.Show(ExecuteCommandSync("ping www.stackoverflow.com"));