背景:
在winform上使用基于Edge内核的Webview2进行嵌套浏览器进行开发。开发的操作系统是64位 win11专业版。
使用Nuget包管理工具安装了Microsoft.Web.WebView2,版本号为1.0.1210.39
问题:在开发机上可以正常打开本地的HTML文件,但是拿到客户机子上(也是win11专业版)却出现空白,无法
打开HTML文件,相关的.NET FRAMEWORK是有安装的。下面是弹出错误提示的图片
相关代码:
var options = new CoreWebView2EnvironmentOptions("--autoplay-policy=no-user-gesture-required");
**//我在网上下载了WebView2一个32位的webview2支行时,path指向的正是解压后的支行时文件夹路径**
string path = AppDomain.CurrentDomain.BaseDirectory + @"Microsoft.WebView2.FixedVersionRuntime.101.0.1210.53.x86";
var environment = await CoreWebView2Environment.CreateAsync(path, null, options);
await webView2Control.EnsureCoreWebView2Async(environment);
string url = AppDomain.CurrentDomain.BaseDirectory + @"Documentation\flex.html";
webView2Control.Source = new Uri(url);//加载本地html文件
请教:是否缺少什么文件呢,要怎么处理?大家有遇到这样问题吗,求指点?
因为webview2是需要自己的runtime的,我们的建议是在启动期间自己先做一个检查和安装runtime的过程
1.先去官方下载runtime安装包
https://developer.microsoft.com/zh-cn/microsoft-edge/webview2/
目前有3种方式的安装包,通常我们选择第一个“长青版”的,这是个在线引导式安装包,体积比较小。
2.把下载下来的exe,放入项目中,同时选择“编译复制”
3.在program.cs里写runtime检查和安装代码
static class Program
{
/// <summary>
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
WebViewInint().Wait();
if (CheckWebView2().instanlled)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FrmBookanShell());
}
else
{
//todo:未正确安装webview runtime处理
MessageBox.Show("Edge webview2 runtime 未正确安装,即将退出程序!");
}
}
public static async Task WebViewInint()
{
var checkResuilt = CheckWebView2();
if (!checkResuilt.instanlled)
{
await installView2().ConfigureAwait(false);
}
}
public static (bool instanlled, string version) CheckWebView2()
{
try
{
var str = CoreWebView2Environment.GetAvailableBrowserVersionString();
if (!string.IsNullOrWhiteSpace(str))
{
return (true, str);
}
}
catch
{
}
return (false, null);
}
public static Task installView2()
{
return Task.Run(() =>
{
using (Process process = new Process())
{
process.StartInfo.UseShellExecute = false;
process.StartInfo.FileName = System.IO.Path.GetFullPath("MicrosoftEdgeWebview2Setup.exe");
process.Start();
process.WaitForExit();
}
});
}
}
经过测试,文件夹名称最好使用英文,不要使用中文,在非中文环境
的系统中会现FileNotFound问题。我测试的机子是英文版的系统。
在其它中文版机子测试都是没有问题的。
感谢wanghui0380,你的代码对我来说也是有参考价值的,谢谢!