加载本地HTML文件在C#web浏览器 [英] Load local HTML file in a C# WebBrowser

查看:705
本文介绍了加载本地HTML文件在C#web浏览器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用我有一个WebBrowser元素。

我想加载本地文件了。

我有一些问题:


  1. 何处放置HTML文件(以便如果用户执行设置它也将安装)

  2. 如何引用文件? (例如,我的猜测是用户的安装文件夹并不总是相同)

修改

我添加HTML文件到我的项目。

和我已经设置它,以便它被复制到输出文件夹。

当我检查是在运行时present:\\ BIN \\调试\\文档\\ index.html的

然而,当我做了我得到的网页浏览器元素的网页无法显示的错误以下。

我用下面的code,试图显示web浏览器的HTML文件。

  WebBrowser1.Navigate时(@。\\文档\\的index.html);


解决方案

  1. 请在右键点击 - >在Visual Studio中的文件属性即可。

  2. 复制到输出目录复制总是

然后,你将能够使用的路径,如 @来引用您的文件。\\ my_html.html

复制到输出目录将会把文件放在同一文件夹中的二进制文件的dll项目时。这适用于任何内容的文件,即使其在子文件夹中。

如果你使用一个子文件夹,这也将在bin文件夹复制所以你的路径然后将 @。\\ my_subfolder \\ my_html.html

为了创建一个URI你可以在本地使用(而不是通过网络servered),你需要使用文件协议,使用二进制文件的基本目录 - 注:此如果设置复制到Ouptut目录如上或路径将不正确才会工作。

这是你所需要的:

 字符串CURDIR = Directory.GetCurrentDirectory();
this.webBrowser1.Url =新的URI(的String.Format(文件:/// {0} /my_html.html,CURDIR));

您必须改弦易辙的变量和名称。

In my app I have a WebBrowser element.

I would like to load a local file in it.

I have some questions:

  1. Where to place the HTML file (so that it will also be installed if a user executes the setup)
  2. how to reference the file? (e.g. my guess is the user's installation folder would not always be the same)

EDIT

I've added the HTML file to my project.

And I have set it up so that it gets copied to output folder.

When I check it it is present when run: \bin\Debug\Documentation\index.html

However when I do the following I get a 'Page cannot be displayed' error in the webbrowser element.

I use the following code to try to display the HTML file in the Webbrowser.

webBrowser1.Navigate(@".\Documentation\index.html");

解决方案

  1. Do a right click->properties on the file in Visual Studio.
  2. Set the Copy to Output Directory to Copy always.

Then you will be able to reference your files by using a path such as @".\my_html.html"

Copy to Output Directory will put the file in the same folder as your binary dlls when the project is built. This works with any content file, even if its in a sub folder.

If you use a sub folder, that too will be copied in to the bin folder so your path would then be @".\my_subfolder\my_html.html"

In order to create a URI you can use locally (instead of servered via the web), you'll need to use the file protocol, using the base directory of your binary - note: this will only work if you set the Copy to Ouptut Directory as above or the path will not be correct.

This is what you need:

string curDir = Directory.GetCurrentDirectory();
this.webBrowser1.Url = new Uri(String.Format("file:///{0}/my_html.html", curDir));

You'll have to change the variables and names of course.

这篇关于加载本地HTML文件在C#web浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆