在C#WebBrows中加载本地HTML文件
在我的应用程序中,我有一个WebBrowser元素。
我想在其中加载本地文件。
我有一些问题:
HTML文件的放置位置(以便用户执行安装程序时也将安装该文件)
如何引用文件? (例如,我的猜测是用户的安装文件夹并不总是相同)
编辑
我已将HTML文件添加到我的项目中。
我已经对其进行设置,以便将其复制到输出文件夹。
当我检查它时,它在运行时存在:\ bin \ Debug \ Documentation \ index.html
但是,当我执行以下操作时,在webbrowser元素中出现“无法显示页面”错误。
我使用以下代码尝试在Webbrowser中显示HTML文件。
webBrowser1.Navigate(@".\Documentation\index.html");
8个解决方案
89 votes
在Visual Studio中的文件上单击鼠标右键->属性。
将复制到输出目录设置为始终复制。
然后,您将可以使用诸如@".\my_subfolder\my_html.html"之类的路径来引用文件。
构建项目时,复制到输出目录会将文件与二进制dll放在同一文件夹中。 这适用于任何内容文件,即使它位于子文件夹中。
如果您使用子文件夹,该文件夹也将被复制到bin文件夹中,因此您的路径将是@".\my_subfolder\my_html.html"
为了创建您可以在本地使用的URI(而不是通过Web服务器),您需要使用文件协议,并使用二进制文件的基本目录-注意:仅当您将Copy设置为Ouptut时,此协议才有效 上面的目录或路径将不正确。
这是您需要的:
string curDir = Directory.GetCurrentDirectory();
this.webBrowser1.Url = new Uri(String.Format("file:///{0}/my_html.html", curDir));
当然,您必须更改变量和名称。
ghostJago answered 2020-01-03T12:55:08Z
13 votes
很晚了,但这是我从谷歌发现的第一击
代替使用当前目录或获取程序集,只需使用Application.ExecutablePath属性:
//using System.IO;
string applicationDirectory = Path.GetDirectoryName(Application.ExecutablePath);
string myFile = Path.Combine(applicationDirectory, "Sample.html");
webMain.Url = new Uri("file:///" + myFile);
mickeymicks answered 2020-01-03T12:55:34Z
5 votes
请注意,file:///方案不适用于紧凑型框架,至少不适用于5.0。
您将需要使用以下内容:
string appDir = Path.GetDirectoryName(
Assembly.GetExecutingAssembly().GetName().CodeBase);
webBrowser1.Url = new Uri(Path.Combine(appDir, @"Documentation\index.html"));
Brett Ryan answered 2020-01-03T12:56:02Z
4 votes
将其放置在“应用程序”设置文件夹中或下面的单独文件夹中
当您的应用运行时,相对于当前目录引用它。
Jan answered 2020-01-03T12:56:28Z
3 votes
在您要运行的装配体附近的某个地方。
使用反射获取执行程序集的路径,然后做一些魔术来定位HTML文件。
像这样:
var myAssembly = System.Reflection.Assembly.GetEntryAssembly();
var myAssemblyLocation = System.IO.Path.GetDirectoryName(a.Location);
var myHtmlPath = Path.Combine(myAssemblyLocation, "my.html");
Andrey Agibalov answered 2020-01-03T12:56:57Z
1 votes
更新上面的@ghostJago答案
对我来说,它作为VS2017中的以下行
string curDir = Directory.GetCurrentDirectory();
this.webBrowser1.Navigate(new Uri(String.Format("file:///{0}/my_html.html", curDir)));
Nouman Bhatti answered 2020-01-03T12:57:23Z
0 votes
对我有用的是
从这里。 我将StartPage.html复制到了xaml文件的相同输出目录,并从该相对路径加载了它。
Alexander Pacha answered 2020-01-03T12:57:48Z
0 votes
Windows 10 uwp应用程序。
尝试这个:
webview.Navigate(new Uri("ms-appx-web:///index.html"));
Ravshanbek Ahmedov answered 2020-01-03T12:58:12Z