WebView2如何加载本地文件?

问题描述

我的 WinForm .NET Framework 4.7.2 中有一个 WebView2 控件,如何在其中加载我的本地 html 文件

我试图用 file:// 扩展名设置 .source 但什么都没有...

这是我尝试过的:

private void Form1_Load(object sender,EventArgs e)
{
    webView.source = new Uri("file://C:/Users/xxx/Desktop/VisualSelf/self.html");
}

解决方法

您可以读取 HTML 文件,然后NavigateToString

if (webView!= null && webView.CoreWebView2 != null)
{
     string text = system.IO.File.ReadAllText(@"C:/Users/xxx/Desktop/VisualSelf/self.html");
     webView.CoreWebView2.NavigateToString(text);
}

或者你可以Navigate到本地文件:

webView.CoreWebView2.Navigate("file:///C:/Users/xxx/Desktop/VisualSelf/self.html");

另外,您需要安装 Microsoft Edge WebView2 Runtime