You try to access a document that is not loaded yet, since you access the Document
property just after you navigate to the a new Uri, and it's why you get a NullReferenceException
.
You need to use the WebBrowser.DocumentCompleted
event.
When does that event get fired ?
From MSDN, the WebBrowser
control navigates to a new document whenever one of the following properties is set or methods is called: Url, DocumentText, DocumentStream, Navigate, GoBack, GoForward, GoHome, GoSearch.
The navigation will trigger the following events in this order:
Navigating
event:
Handle the Navigating event to receive notification before navigation
begins. Handling this event lets you cancel navigation if certain
conditions have not been met, for example, when the user has not
completely filled out a form.
Navigated
event:
Handle the Navigated event to receive notification when the WebBrowser
control finishes navigation and has begun loading the document at
the new location.
DocumentCompleted
event:
Handle the DocumentCompleted event to receive notification when the
new document finishes loading. When the DocumentCompleted event
occurs, the new document is fully loaded, which means you can access
its contents through the Document, DocumentText, or DocumentStream
property.
I have the control invisible.It is not supposed to be used by the
user.I am just trying to load a document from the code-behind
The fact the control is not visible shouldn't be a problem. I have tested with a webbrowser
created at runtime that I have not added to a form (see sample below), and the event is still raised.
How does it get activated?
Here is a possible implementation:
private WebBrowser wb;
private void Button1_Click(System.Object sender, System.EventArgs e)
{
if (wb == null) {
wb = new WebBrowser();
wb.DocumentCompleted += wb_DocumentCompleted;
}
wb.Navigate("YourPath");
}
private void wb_DocumentCompleted(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
{
IO.File.WriteAllText(IO.Path.Combine(Application.StartupPath, "Test.html"), wb.Document.Body.Parent.OuterHtml, System.Text.Encoding.GetEncoding(wb.Document.Encoding));
}
See also this thread Can I wait for a webbrowser to finish navigating, using a for loop?