因DLL版本错误引发System.BadImageFormatException问题求助
问题背景
编译引用外部Windows DLL的应用时,抛出以下异常:
发生类型为'System.BadImageFormatException'的异常,位于mscorlib.dll中但未在用户代码中处理
附加信息: 无法加载文件或程序集'System.Runtime.WindowsRuntime, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'或其依赖项。不应加载引用程序集以执行,它们只能在仅反射加载器上下文中加载。
引用的DLL路径为C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5.1\System.Runtime.WindowsRuntime.dll,已尝试以下方案但未解决:
- 删除/bin和/obj文件夹
- 将平台目标改为X86
- 移除并重新添加该DLL引用
- 确认目标框架为4.5.1
- 将引用DLL的“特定版本”设为False
- 检查.csproj中已添加正确引用:
<Reference Include="System.Runtime.WindowsRuntime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5.1\System.Runtime.WindowsRuntime.dll</HintPath> </Reference>
尝试用gacutil命令将DLL添加到GAC时,报错:
添加程序集到缓存失败: 尝试加载格式不正确的程序。
可行解决建议
替换引用程序集为运行时版本
Reference Assemblies目录下的文件仅用于编译时校验,不能在运行时执行。需将引用替换为运行时版本的DLL,可从C:\Windows\Microsoft.NET\Framework\v4.0.30319(x86)或C:\Windows\Microsoft.NET\Framework64\v4.0.30319(x64)目录中获取对应架构的运行时DLL。添加程序集绑定重定向
在App.config或Web.config中加入绑定重定向规则,强制加载指定版本,避免编译器自动加载冲突版本:
<configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="System.Runtime.WindowsRuntime" publicKeyToken="b77a5c561934e089" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-4.0.10.0" newVersion="4.0.0.0" /> </dependentAssembly> </assemblyBinding> </runtime> </configuration>
清理GAC中的冲突版本
先执行gacutil /l System.Runtime.WindowsRuntime查看GAC中已安装的版本列表,若存在4.0.10.0等冲突版本,用命令gacutil /u System.Runtime.WindowsRuntime, Version=4.0.10.0, PublicKeyToken=b77a5c561934e089卸载对应版本。设置引用的“复制本地”为True
右键项目中的System.Runtime.WindowsRuntime引用,将“复制本地”属性设为True,确保运行时项目输出目录下存在正确版本的DLL,避免加载系统中其他冲突副本。严格匹配DLL架构与项目平台
确认引用的DLL架构(x86/x64/MSIL)和项目的平台目标完全一致:- 若项目平台为X86,需引用x86架构的运行时DLL
- 若项目为AnyCPU,需引用MSIL通用架构的DLL
内容的提问来源于stack exchange,提问作者Cainnech

