我在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。
请帮忙。