简体   繁体   English

将本地网页加载到webbrowser控件中

[英]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. 我试图将webbrowser控件添加到窗口中,然后打开页面。 I tried a web URL as well as a local HTML file to no avail. 我尝试使用Web URL以及本地HTML文件都无济于事。 Here is my code: 这是我的代码:

namespace qTab1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); 命名空间qTab1 {公共子类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. 发生这种情况的原因是,当您按Debug或以任何其他方式构建项目时,根目录是可执行文件的目录(因此它将是-./bin/Debug ),而不是项目的目录。

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 . 右键单击html文件,单击“ 属性 ”,然后将变量“ 复制到输出目录 ”设置为“ 始终复制 ”。 That way, the html file will get copied with your executable. 这样,html文件将与可执行文件一起复制。
  2. Now you have to load the local file into the WebBrowser control. 现在,您必须将本地文件加载到WebBrowser控件中。 The following should work : 以下应该工作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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