David Tunnell
David Tunnell

Reputation: 7542

Load a local webpage into the webbrowser control

I am trying to simply add a webbrowser control to a window and then have it open up a page. I tried a web URL as well as a local HTML file to no avail. Here is my code:

namespace qTab1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); }

    private void Form1_Load(object sender, EventArgs e)
    {
        FileStream source = new FileStream("index.html", FileMode.Open, FileAccess.Read);
        webBrowser1.DocumentStream = source;
        //// When the form loads, open this web page.
        //webBrowser1.Navigate("www.google.com");
    }

    private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
    {
        // Set text while the page has not yet loaded.
        this.Text = "Navigating";
    }

    private void webBrowser1_DocumentCompleted(object sender,
        WebBrowserDocumentCompletedEventArgs e)
    {
        // Better use the e parameter to get the url.
        // ... This makes the method more generic and reusable.
        this.Text = e.Url.ToString() + " loaded";
    }
}

}

This is my project at the moment:

enter image description here

What am I doing wrong?

Upvotes: 0

Views: 1592

Answers (1)

user3352250
user3352250

Reputation: 326

The reason this happens is that when you press Debug or build your project any other way the root directory is the directory of the executable (so it would be - ./bin/Debug), not the directory of the project.

To fix this, you can do the following:

  1. Right click the html file, click Properties and set the variable "Copy to output directory" to Copy always. That way, the html file will get copied with your executable.
  2. Now you have to load the local file into the WebBrowser control. The following should work :

    webBrowser1.Url = new Uri("file:///" + Directory.GetCurrentDirectory() + "/index.html");

Upvotes: 2

Related Questions