Skip to main content
 首页 » 编程设计

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

2024年01月01日44落叶

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

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