【问题标题】:Using .NET Framework 4.8 WinForm webView control to display local html使用.NET Framework 4.8 WinForm webView控件显示本地html
【发布时间】:2019-10-21 17:00:59
【问题描述】:

我需要显示一个本地 HTML 文件,其中包含通过外部或内部样式表包含的图像和字体。我想将 .NET Framework 4.8 引入的新 webView 控件用于 WinForms。

我尝试了几种不同的方法。使用字体和图像托管 HTTP 服务器确实有效。遗憾的是,在推出该程序时,这不是一个解决方案,因为它对每台个人电脑的配置太多。

将图像和字体编码为 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 还是我不知道的潜在问题?

如果您知道在 WinForm 中使用 webView 控件打开 someLocalPath HTML 文件的任何其他方法,请告诉我。

【问题讨论】:

标签: c# .net winforms webview


【解决方案1】:

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 的实现中对本地文件名进行了硬编码。

【讨论】:

    【解决方案2】:

    不要使用当前目录或获取程序集,只需使用 Application.ExecutablePath 属性:

    //using System.IO;  
    
    string applicationDirectory = Path.GetDirectoryName(Application.ExecutablePath);
    
    string myFile = Path.Combine(applicationDirectory, "Sample.html");
    
    webMain.Url = new Uri("file:///" + myFile);
    

    【讨论】:

      猜你喜欢
      • 2010-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-15
      • 1970-01-01
      • 2019-06-14
      • 2020-10-14
      • 1970-01-01
      相关资源
      最近更新 更多