我需要显示通过外部或内部样式表包含的图像和字体的本地HTML文件。我想使用.NET Framework4.8为WinForms引入的新webView控件。
我尝试了几种不同的方法。使用字体和图像托管HTTP服务器可以正常工作。遗憾的是,在推出该程序时,这不是一个解决方案,因为对于每台单独的pc来说,它的配置太多了。
将图像和字体编码为base64字符串并将其用作源确实有效。但我希望使用NavigateToLocalStreamUri方法来获得一个易于阅读且不需要太多开销即可工作的解决方案。
NuGet软件包Microsoft.Toolkit.Forms.UI.Controls.WebView安装在其最新的稳定版本5.1.1中
下面是我当前用来尝试运行NavigateToLocalStreamUri的代码。
var uri = new Uri(someLocalPath);
webView1.NavigateToLocalStreamUri(uri, new CustomUriToStreamResolver());
private class CustomUriToStreamResolver : IUriToStreamResolver
{
public Stream UriToStream(Uri uri)
{
var stream = new FileStream(uri.AbsolutePath, FileMode.Open);
return stream;
}
}
预期的行为是打开位于someLocalPath
的HTML文件,而不是抛出以下异常,这是我不完全理解的。
Could not find any resources appropriate for the specified culture or the
neutral culture. Make sure \"Microsoft.Toolkit.Win32.UI.Controls.DesignerUI.resources\"
was correctly embedded or linked into assembly
\"Microsoft.Toolkit.Forms.UI.Controls.WebView\" at compile time, or that all
the satellite assemblies required are loadable and fully signed.
是我的CustomUriToStreamResolver
出了问题,还是有我不知道的潜在问题?
如果您知道在someLocalPath
中使用webView控件打开WinForm HTML文件的任何其他方法,请务必让我知道。
发布于 2019-11-30 04:04:32
不使用当前目录或获取程序集,只需使用Application.ExecutablePath属性:
//using System.IO;
string applicationDirectory = Path.GetDirectoryName(Application.ExecutablePath);
string myFile = Path.Combine(applicationDirectory, "Sample.html");
webMain.Url = new Uri("file:///" + myFile);
发布于 2020-03-25 08:29:38
webView.NavigateToLocal("local file")
似乎起作用了:
this.webView.NavigateToLocal(".\\file.html");
我不确定为什么导航不能工作。
编辑: Visual Studio将NavigateToLocal显示为已过时,并改为使用NavigateToLocalStreamUri。参见https://docs.microsoft.com/en-us/uwp/api/windows.ui.xaml.controls.webview.navigatetolocalstreamuri。
编辑#2:我无法让NavigateToLocalStreamUri使用引用本地文件的Uri。我最终在我的IUriToStreamResolver实现中硬编码了本地文件名。
https://stackoverflow.com/questions/56473108
复制相似问题