[英]Load local HTML file in a C# WebBrowser
在我的应用程序中,我有一个 WebBrowser 元素。
我想在其中加载一个本地文件。
我有一些问题:
编辑
我已将 HTML 文件添加到我的项目中。
我已经对其进行了设置,以便将其复制到输出文件夹。
当我检查它时,它在运行时存在:\\bin\\Debug\\Documentation\\index.html
但是,当我执行以下操作时,我在 webbrowser 元素中收到“无法显示页面”错误。
我使用以下代码尝试在 Webbrowser 中显示 HTML 文件。
webBrowser1.Navigate(@".\Documentation\index.html");
然后,您将能够使用诸如@".\\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));
当然,您必须更改变量和名称。
很晚了,但这是我从谷歌找到的第一个热门
而不是使用当前目录或获取程序集,只需使用Application.ExecutablePath
属性:
//using System.IO;
string applicationDirectory = Path.GetDirectoryName(Application.ExecutablePath);
string myFile = Path.Combine(applicationDirectory, "Sample.html");
webMain.Url = new Uri("file:///" + myFile);
请注意, file:///
方案不适用于紧凑型框架,至少不适用于 5.0。
您将需要使用以下内容:
string appDir = Path.GetDirectoryName(
Assembly.GetExecutingAssembly().GetName().CodeBase);
webBrowser1.Url = new Uri(Path.Combine(appDir, @"Documentation\index.html"));
像这样:
var myAssembly = System.Reflection.Assembly.GetEntryAssembly();
var myAssemblyLocation = System.IO.Path.GetDirectoryName(a.Location);
var myHtmlPath = Path.Combine(myAssemblyLocation, "my.html");
对我有用的是
<WebBrowser Source="pack://siteoforigin:,,,/StartPage.html" />
从这里。 我将 StartPage.html 复制到与 xaml 文件相同的输出目录,并从该相对路径加载它。
Windows 10 uwp
应用程序。
试试这个:
webview.Navigate(new Uri("ms-appx-web:///index.html"));
更新上面的@ghostJago 答案
对我来说,它在VS2017
作为以下几行VS2017
string curDir = Directory.GetCurrentDirectory();
this.webBrowser1.Navigate(new Uri(String.Format("file:///{0}/my_html.html", curDir)));
我一直在尝试不同的答案,但设法得出了一些有用的东西,这里是:
1- 在我在项目级别创建的名为 WebPagesHelper 的文件夹中添加了页面
2- 要由 webBrowser Control 打印页面,
string curDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
var uri = new Uri(curDirectory);
string myFile = Path.Combine(uri.AbsolutePath, @"WebPagesHelper\index.html");
Uri new_uri = new Uri(myFile);
我必须获取程序集路径,创建第一个 uri 以获取不附加“file://”的绝对路径,接下来我将此绝对路径与其文件夹中页面的相对路径结合起来,然后从结果。
然后将其传递给 webBrowser URL 属性webBrowser.URL = new_uri;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.