Home > Mobile >  Mapping WebView2 to a relative path
Mapping WebView2 to a relative path

Time:03-02

I am working on a WPF project (Visual Studio 2022 and Net 6.0). I have local html file within a folder in my project (MyNotices). I have WebView2 in the xaml code as shown below

    <DockPanel Width="1200" Height="600" Visibility="Visible" x:Name="web1">
             <wv2:WebView2 x:Name="webView"  Width="{Binding ElementName=CurrentPresenter, Path=ActualWidth}" 
                           Height="{Binding ElementName=CurrentPresenter, Path=ActualHeight}" Source=""/>
    </DockPanel>

I would like to map the source of the webview to the local html file. It is working well if I use absolute path to the html file as shown below

       await webView.EnsureCoreWebView2Async();
       webView.Source = new Uri("/C:/Users/xxxx/source/repos/MyNotices/Local/RichText.html");

I would like to use a relative path and I am using the SetVirtualHostNameToFolderMapping Here is the code

  await webView.EnsureCoreWebView2Async(); // ensure the CoreWebView2 is created
          webView.CoreWebView2.SetVirtualHostNameToFolderMapping(
            "appassets", "Local", CoreWebView2HostResourceAccessKind.Allow);
             webView.Source = new Uri("http://appassets/RichText.html");

Here is the location of my app.exe file C: \Users\xxxx\source\repos\MyNotices\bin\Debug\net6.0-windows\MyNotices.exe.

I get this error message - System.IO.DirectoryNotFoundException: 'The system cannot find the path specified. (0x80070003)'. Any help would be appreciated

CodePudding user response:

You example works assuming the file Local/RichText.html is located in the output folder of the .exe, i.e. in C:\Users\xxxx\source\repos\MyNotices\bin\Debug\net6.0-windows\Local\RichText.html.

From the docs:

For example, after calling SetVirtualHostNameToFolderMapping("appassets.example", "assets", CoreWebView2HostResourceAccessKind.Deny);, navigating to https://appassets.example/my-local-file.html will show content from my-local-file.html in the assets subfolder located on disk under the same path as the app's executable file.

So add the Local/RichText.html file to your project in Visual Studio and set its Build Action property to Content and its Copy to Output Directory property to Copy if newer.

If the file is located outside of your app's output directory you should use an absolute path to access it. The relative path refers to a file within the folder of the .exe.

  • Related