Any CPU编译的.NET Framework项目如何按运行架构加载对应WebView2Loader.dll?
.NET Framework C# Any CPU模式下根据运行架构加载对应版本WebView2Loader.dll
问题背景
我的Visual Studio .NET Framework C#项目采用Any CPU编译模式,但WebView2Loader.dll存在32位和64位版本。已在.csproj文件中配置如下,确保两个版本分别复制到输出目录的WebView2Loader64和WebView2Loader86子目录:
<Content Include="$(MSBuildThisFileDirectory)bin\$(Configuration)\runtimes\win-x64\native\WebView2Loader.dll"> <Link>WebView2Loader64\%(Filename)%(Extension)</Link> <PublishState>Included</PublishState> <Visible>False</Visible> <CopyToOutputDirectory>Always</CopyToOutputDirectory> <Pack>false</Pack> </Content> <Content Include="$(MSBuildThisFileDirectory)bin\$(Configuration)\runtimes\win-x86\native\WebView2Loader.dll"> <Link>WebView2Loader86\%(Filename)%(Extension)</Link> <PublishState>Included</PublishState> <Visible>False</Visible> <CopyToOutputDirectory>Always</CopyToOutputDirectory> <Pack>false</Pack> </Content>
需要实现应用根据运行时的系统架构,自动加载对应版本的WebView2Loader.dll。
解决方案
1. 在应用启动时动态加载对应架构的DLL
Any CPU模式下应用的运行架构是在启动时确定的,因此需要在入口处添加动态加载逻辑,判断当前进程位数后加载对应目录的DLL。
在项目的入口文件(如Program.cs)中添加以下代码:
using System; using System.Runtime.InteropServices; using System.Windows.Forms; namespace YourProjectNamespace { static class Program { // 导入Windows API加载原生DLL [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] private static extern IntPtr LoadLibrary(string lpFileName); [STAThread] static void Main() { // 确定要加载的DLL路径 string dllSubDir = Environment.Is64BitProcess ? "WebView2Loader64" : "WebView2Loader86"; string dllPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, dllSubDir, "WebView2Loader.dll"); // 加载DLL IntPtr dllHandle = LoadLibrary(dllPath); if (dllHandle == IntPtr.Zero) { // 加载失败时抛出异常,可根据需求替换为提示框等逻辑 throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); } // 启动应用主窗体 Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } } }
2. 处理Any CPU的"Prefer 32-bit"选项
如果项目的Any CPU设置中勾选了Prefer 32-bit,即使在64位系统上,应用也会以32位进程运行,此时会自动加载32位版本的DLL;若未勾选,则64位系统上运行64位进程加载64位DLL,32位系统上加载32位DLL。
注意事项
- 编译后需验证输出目录中
WebView2Loader64和WebView2Loader86目录及其下的DLL文件是否存在。 - 若为WPF项目,只需将WinForms启动代码替换为WPF的
Application.Run(new MainWindow())即可。
内容的提问来源于stack exchange,提问作者nomacreates
相关产品推荐
相关产品推荐

