Reputation: 3939
I create a Windows application in C# 4.0. I try to create a dynamic WebBrowser
.
This function works inside the loop. Please see my function code below:
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();
}
}
Sometimes, browser.Document.Write(html)
shows this error.
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
I added browser.Document.OpenNew(true);
in my code. My OS is Windows XP and browser is IE8.
Please help.
Upvotes: 2
Views: 3913