升级Win11 24H2后导入System.Runtime.CompilerServices.Unsafe版本异常
解决Windows 11 24H2下Selenium 4.27.0依赖System.Runtime.CompilerServices.Unsafe版本不匹配问题
针对你遇到的Win11 24H2升级后Selenium脚本无法找到4.0.4.1版本System.Runtime.CompilerServices.Unsafe的问题,可按以下方向排查解决:
检查全局程序集缓存(GAC)版本差异
Win11 24H2的系统更新可能替换了GAC中该程序集的版本,导致PowerShell优先加载系统自带的4.0.4.0而非共享模块中的4.0.4.1:
- 分别在两台机器上以管理员权限运行PowerShell,执行命令:
gacutil /l System.Runtime.CompilerServices.Unsafe - 对比输出的版本列表,如果24H2机器只有4.0.4.0版本,可将共享模块中4.0.4.1版本的DLL安装到GAC:
gacutil /i "共享路径\System.Runtime.CompilerServices.Unsafe.dll"
添加程序集绑定重定向配置
通过配置文件强制.NET运行时重定向程序集版本,忽略系统自带的低版本:
- 在PowerShell可执行文件目录(通常是
C:\Windows\System32\WindowsPowerShell\v1.0)或你的脚本/模块所在目录,创建powershell.exe.config文件,内容如下:<configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-4.0.4.0" newVersion="4.0.4.1" /> </dependentAssembly> </assemblyBinding> </runtime> </configuration> - 这个配置会让运行时把所有对0.0.0.0到4.0.4.0版本的请求,自动转向4.0.4.1版本。
手动指定程序集加载路径
在脚本开头添加程序集解析事件,强制加载共享模块中的指定版本DLL:
# 注册程序集解析事件 $resolveHandler = [System.ResolveEventHandler]{ param($sender, $args) $asmName = [System.Reflection.AssemblyName]::new($args.Name) if ($asmName.Name -eq "System.Runtime.CompilerServices.Unsafe" -and $asmName.Version -eq [version]"4.0.4.1") { # 替换为你的共享模块中该DLL的实际路径 $targetPath = "\\共享网络路径\modules\System.Runtime.CompilerServices.Unsafe.dll" return [System.Reflection.Assembly]::LoadFrom($targetPath) } return $null } [System.AppDomain]::CurrentDomain.add_AssemblyResolve($resolveHandler) # 你的Selenium脚本代码... # 脚本结束后移除事件(可选) [System.AppDomain]::CurrentDomain.remove_AssemblyResolve($resolveHandler)
验证共享模块的DLL版本完整性
即使文件大小一致,也可能存在DLL版本被无意替换的情况:
- 右键共享模块中的
System.Runtime.CompilerServices.Unsafe.dll,选择「属性」→「详细信息」,确认文件版本和产品版本是否为4.0.4.1; - 如果版本不符,重新从
system.runtime.compilerservices.unsafe.4.5.3.nupkg中提取NetStandard2.0目录下的DLL,替换共享位置的文件。
内容的提问来源于stack exchange,提问作者AceOfSpades
相关产品推荐
相关产品推荐

