-1

I want to save the web page source code and I have the following code:

WebBrowser browser = new WebBrowser();
browser.ScriptErrorsSuppressed = true;
int SleepTime = 5000;
loadPage: browser.Navigate("https://google.com");
System.Threading.Thread.Sleep(SleepTime);
MessageBox.Show("browser.Navigae OK");
if(browser.ReadyState == WebBrowserReadyState.Complete)
{
    string path = @"htmlCode.txt";
    if(browser.Document.Body.Parent.InnerText != null)
    {
        File.WriteAllText(path, browser.Document.Body.Parent.OuterHtml, Encoding.GetEncoding(browser.Document.Encoding));
        MessageBox.Show("Success! htmlCode.txt created");
        break;
    }
    else
    {
        MessageBox.Show("browser.Document.Body.Parent.InnerText=" + browser.Document.Body.Parent.InnerText);
        MessageBox.Show("Failure htmlCode.txt not created");
    }
}

if I comment

MessageBox.Show("browser.Navigate OK");

my code it is not working... why?

Daxtron2
  • 1,239
  • 1
  • 11
  • 19
Kadar Barna
  • 11
  • 2
  • 2

1 Answers1

-1

Why is it not working?

Typical Race condition

Navigation takes time to finish. Your MessageBox.Show acts like a huge delay buffer which gives web browser enough time to finish the operation.

You should be using DocumentCompleted event to ensure this does not happen.

Steve
  • 11,696
  • 7
  • 43
  • 81
  • **1-** *Race condition* is commonly used when threads are involved. In OP's case, there is a single thread (UI thread). **2-** *DocumentCompleted* is the correct event. Navigated doesn't guarantee that the page is ready to use DOM objects – L.B May 31 '18 at 19:00
  • @L.B there is UI thread + webbrowser background thread. UI thread enters processing stage before background thread completes. I do think its considered a race condition. Updated the document completed part. – Steve May 31 '18 at 19:05
  • 1
    There is **no** *webbrowser background thread*. WB control works in UI thread. If you block the UI thread (like Thread.Sleep), WB is also blocked. – L.B May 31 '18 at 19:06