在控制台应用程序中,我需要捕获输出。有两种情况:
- Internet 无法显示网页
- 互联网正常。
我正在使用下面的代码
using(WebClient client = new WebClient())
{
string pageData;
try
{
pageData = client.DownloadString("https://google.com");
}
catch (HttpListenerException e)
{
Console.WriteLine("Exception is" + e);
}
这里我需要应用一个条件,如果 Internet Explorer 显示“Internet Explorer 无法显示该网页”,那么它应该显示无连接。我需要捕获输出。
最佳答案
您需要捕获 Web 客户端因任何原因无法下载页面时抛出的 WebException。试试这个:
public static bool IsAlive(string url)
{
bool isAlive = false;
using (WebClient client = new WebClient())
{
try
{
var content = client.DownloadString(url);
// if we got this far there was no error fetching the content
isAlive = true;
}
catch (WebException ex)
{
// could not fetch page - can output reason here if required
Console.WriteLine("Error when fetching {0}: {1}", url, ex);
}
}
return isAlive;
}
参见 WebClient有关详细信息,请访问 MSDN。
关于c# - 在 C# 中捕获 Web 浏览器输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12659712/