HtmlAgilityPack.dll中发生“System.StackOverflowException”

时间:2015-07-10 10:14:25

标签: c# asp.net dll html-agility-pack

我试图使用HtmlAgilityPack.dll废弃页面,但是一些url进入函数,我收到了错误,我无法在try-catch块中捕获它。那么有人可以帮助我吗?

错误: HtmlAgilityPack.dll中出现未处理的“System.StackOverflowException”类型异常

public void HtmlLoad(string url)
    {
        try
        {
            HttpWebRequest myHttpWebRequest = null;     //Declare an HTTP-specific implementation of the WebRequest class.
            HttpWebResponse myHttpWebResponse = null;   //Declare an HTTP-specific implementation of the WebResponse class
            //Create Request  // 
            myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
            myHttpWebRequest.Method = "GET";
            myHttpWebRequest.ContentType = "text/html; encoding='utf-8'";
            //Get Response
            myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();

            Stream data = myHttpWebResponse.GetResponseStream();//client.OpenRead(url);
            doc.Load(data);
            data.Close();

        }
        catch (Exception ex) { throw ex; }
    }

1 个答案:

答案 0 :(得分:0)

你可以尝试这个干净的

 public static async Task<int> HtmlLoadAsync(string url/*, bool addUserAgent = false*/)
    {
        try
        {
            var client = new HttpClient();
            //if (addUserAgent)                 OPTIONAL 
            //{
            //    client.DefaultRequestHeaders.UserAgent.ParseAdd(UserAgent);
            //}
            //client.Timeout = TimeOut;
            var response = client.GetStringAsync(url);
            var urlContents = await response;
            var document = new HtmlAgilityPack.HtmlDocument();
            document.LoadHtml(urlContents);
            // process document now
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        return 0;
    }

现在称之为

private async void Process()
{
  await HtmlLoadAsync("http://....");
}