Sarit Yefet
Sarit Yefet

Reputation: 3

How do I know when a website finished loaded into WebBrowser?

First i have this button click event:

private void toolStripButton3_Click(object sender, EventArgs e)
{
    GetHtmls();
}

Then the method GetHtmls:

private void GetHtmls()
{
    for (int i = 1; i < 2; i++)
    {
        adrBarTextBox.Text = sourceUrl + i;
        getCurrentBrowser().Navigate(adrBarTextBox.Text);
        targetHtmls = (combinedHtmlsDir + "\\Html" + i + ".txt");
    }
}

Now the loop is for one html but later i will change the loop to be i < 45

getCurrentBrowser method:

private WebBrowser getCurrentBrowser()
{
    return (WebBrowser)browserTabControl.SelectedTab.Controls[0];
}

Then in the load form1 event I have:

browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(Form1_DocumentCompleted);

And the completed event:

private void Form1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    WebBrowser currentBrowser = getCurrentBrowser();           
    StreamWriter writer = File.CreateText(targetHtmls);
    writer.Write(getCurrentBrowser().DocumentText);
    writer.Close();
}

What I'm doing here is loading the html to the web browser and create a file on the hard disk of the html source content. But i'm getting two problems:

  1. In the completed event it keep calling the completed event and create the html file over and over again untill the codument is loaded. How can i make that it will do it once in the completed event ? I mean that it will wait untill the dosument loaded and then write to the file and create the file only once ?

  2. How do I make it all when the loop will be i < 45 and not 2? So it will wait for the first html to be loaded then write to the file when finish the writing make the next html in the loop then write again in the completed event and so on so it will not move on each other one.

The completed event of the web browser document doesn't act like other completed events it keep calling the completed event every second or so until it finish loading the html.

Upvotes: 0

Views: 164

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 156968

I am not sure what the purpose of the WebBrowser is in this case. That control is for human interaction, not loading X number of sites.

I would recommand to use HttpWebRequest or the newer WebClient class. This is much easier to use in the case you show here.

The WebClient class can be used like this:

WebClient wc = new WebClient();
string html = wc.DownloadString("yourUrl");

This will wait until the request is completed and the result is returned. No need for event handlers or such. You could improve the performance by using async though.

Upvotes: 1

Related Questions