简体   繁体   中英

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:

在此处输入图片说明

What am I doing wrong?

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM