Using .NET Framework 4.8 WinForm webView control to display local html

Viewed 2217

I need to display a local HTML file with both images and fonts that are included via an external or internal style sheet. I want to use the new webView control introduced with .NET Framework 4.8 for WinForms.

I tried a few different ways. Hosting an HTTP Server with the font and the images do work. Sadly that's not a solution when rolling out the program as it is too much configuration for each individual pc.

Encoding the images and font to base64 strings and using them as the source does work. But I would like to use the NavigateToLocalStreamUri Method to have a solution which is easy to read and doesn't need too much overhead to make it work.

The NuGet package Microsoft.Toolkit.Forms.UI.Controls.WebView is installed in its most recent stable version 5.1.1

Below you see the code I am currently using to try and get the NavigateToLocalStreamUri running.

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;
            }
        }

The expected behaviour is opening the HTML file that is located at someLocalPath Instead it throws the following exception, which I do not fully understand.

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.

Is the problem my CustomUriToStreamResolver or is there an underlying issue I am unaware of?

If you know of any other way to open the someLocalPath HTML file with the webView control in WinForm please do let me know.

2 Answers

Instead of using the current directory or getting the assembly, just use the Application.ExecutablePath property:

//using System.IO;  

string applicationDirectory = Path.GetDirectoryName(Application.ExecutablePath);

string myFile = Path.Combine(applicationDirectory, "Sample.html");

webMain.Url = new Uri("file:///" + myFile);

webView.NavigateToLocal("local file") seems to work:

this.webView.NavigateToLocal(".\\file.html");

I'm not sure why Navigate doesn't work.

EDIT: Visual Studio shows NavigateToLocal as obsolete and to use NavigateToLocalStreamUri instead. See https://docs.microsoft.com/en-us/uwp/api/windows.ui.xaml.controls.webview.navigatetolocalstreamuri.

EDIT #2: I was not able to get NavigateToLocalStreamUri to work with a Uri that refers to the local file. I ended up hard coding the local file name in my implementation of IUriToStreamResolver.

Related