2

我在 C# 4.0 中创建了一个 Windows 应用程序。我尝试创建一个动态的WebBrowser.

此函数在循环内工作。请看下面我的功能代码:

public WebBrowser GetLoadText(string url)
{
    string html = string.Empty;
    WebBrowser browser = new WebBrowser();
    using (WebClient client = new WebClient())
    {
        Uri innUri = null;
        if (!url.StartsWith("http://"))
        url = "http://" + url;
        if (url.EndsWith("."))
        innUri = ManipulateBrokenUrl(url);
        else
        Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out innUri);
        try
        {
            LogWriter.WriteLog(" Proxy is : " + client.Proxy.ToString(), "GetLoadTextException");
            client.Headers.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)");
            html = client.DownloadString(innUri);
            if (!string.IsNullOrEmpty(html))
            {
                browser.DocumentText = html;
                browser.AllowWebBrowserDrop = false;
                browser.ScriptErrorsSuppressed = true;
                browser.Document.Write(html);
                return browser;
            }
            else
            {
                return new WebBrowser();
            }
        }
        catch (WebException we)
        {
            LogWriter.WriteLog(" ", "GetLoadTextException");
            LogWriter.WriteLog(" Proxy is : " + client.Proxy.ToString(), "GetLoadTextException");
            LogWriter.WriteLog("WebException Status : " + we.Status, "GetLoadTextException");
            LogWriter.WriteLog("WebException Message : " + we.Message, "GetLoadTextException");
            if (we.Status == WebExceptionStatus.ProtocolError)
            {
                LogWriter.WriteLog("WebException Status Code : " + ((HttpWebResponse)we.Response).StatusCode, "GetLoadTextException");
                LogWriter.WriteLog("WebException Status Description : " + ((HttpWebResponse)we.Response).StatusDescription, "GetLoadTextException");
            }
            if (((HttpWebResponse)we.Response).StatusCode != HttpStatusCode.NotFound)
            {
                LogWriter.WriteLog("Start Thread Sleep After the WebException caught", "GetLoadTextException");
                LogWriter.WriteLog("Resume the extraction process after the sleep and over come the Server Timeout issue.", "GetLoadTextException");
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            browser = null;
            client.Dispose();
        }
        return new WebBrowser();
    }
}

有时,browser.Document.Write(html)显示此错误。

尝试读取或写入受保护的内存。这通常表明其他内存已损坏。

在此处输入图像描述

browser.Document.OpenNew(true);在我的代码中添加了。我的操作系统是 Windows XP,浏览器是 IE8。

请帮忙。

4

0 回答 0