c# - 在 C# 中捕获 Web 浏览器输出

标签 c#

在控制台应用程序中,我需要捕获输出。有两种情况:

  • 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/

相关文章:

c# - AuthenticationManager.SignIn() 不存在于 AuthenticationManager 类中

c# - .NET 4.0 中的 CallerMemberName 不起作用

c# - 训练 tesseract 后 tessdata 文件夹中应该包含哪些文件?

c# - dotnet core 3.1 windows 服务无法加载配置设置

c# - 排序列表 <矩形>

c# - 为什么 Browsable 属性使属性不可绑定(bind)?

c# - 下拉菜单选择在 Phantomjs 上使用 C# selenium 不起作用

Delphi 开发人员的 C# 标准/风格?

c# - 哪个是性能最好的 : XPathNavigator with XPath vs Linq to Xml with query?

c# - 如果我们同步等待结果,使用任务有什么好处吗?