我正在開發一個 WPF 專案(Visual Studio 2022 和 Net 6.0)。我的專案(MyNotices)的檔案夾中有本地 html 檔案。我在 xaml 代碼中有 WebView2,如下所示
<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>
我想將 webview 的源映射到本地 html 檔案。如果我使用 html 檔案的絕對路徑,則效果很好,如下所示
await webView.EnsureCoreWebView2Async();
webView.Source = new Uri("/C:/Users/xxxx/source/repos/MyNotices/Local/RichText.html");
我想使用相對路徑,我正在使用SetVirtualHostNameToFolderMapping 這是代碼
await webView.EnsureCoreWebView2Async(); // ensure the CoreWebView2 is created
webView.CoreWebView2.SetVirtualHostNameToFolderMapping(
"appassets", "Local", CoreWebView2HostResourceAccessKind.Allow);
webView.Source = new Uri("http://appassets/RichText.html");
這是我的 app.exe 檔案 C 的位置:\Users\xxxx\source\repos\MyNotices\bin\Debug\net6.0-windows\MyNotices.exe。
我收到此錯誤訊息 - System.IO.DirectoryNotFoundException:'系統找不到指定的路徑。(0x80070003)'。任何幫助,將不勝感激
uj5u.com熱心網友回復:
您的示例作業假設檔案Local/RichText.html位于 的輸出檔案夾中.exe,即C:\Users\xxxx\source\repos\MyNotices\bin\Debug\net6.0-windows\Local\RichText.html.
從檔案:
例如,呼叫 后
SetVirtualHostNameToFolderMapping("appassets.example", "assets", CoreWebView2HostResourceAccessKind.Deny);,導航到https://appassets.example/my-local-file.html將顯示 my-local-file.html 中的內容,該內容位于磁盤上與應用程式的可執行檔案相同的路徑下的 assets 子檔案夾中。
因此,將Local/RichText.html檔案添加到 Visual Studio 中的專案中,并將其屬性Build Action設定為.ContentCopy to Output DirectoryCopy if newer
如果檔案位于應用程式的輸出目錄之外,您應該使用絕對路徑來訪問它。相對路徑是指.exe.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/436194.html
