未能加载文件或程序集或它的某一个依赖项,系统找不到指定的文件

解決不同版本依赖问题

1. 问题描述

一个项目引用不同版本的同一DLL,会引发以下报错:

未能加载文件或程序集“xxx, Version=x.x.x.x, Culture=neutral, PublicKeyToken=xxxxxxxxxxxx”或它的某一个依赖项。系统找不到指定的文件

这里来解决项目中同一DLL的多版本问题。

2. 解决方式

通过配置配置文件(app.config[控制台或窗体应用等]或web.config[Web项目])增加配置节点dependentAssembly

不同场景有不同的解决方式,下面说明

场景一、以高版本兼容

例如:新旧项目都引用Newtonsoft.Json,但是不同版本。需要以最高版本兼容时:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
  </appSettings>
  <system.web>
  </system.web>
  <system.webServer>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

场景二、同一DLL两种版本共存

例如:项目自己引用log4net.dll 版本1.2.13.0 。添加第三方某个dll,第三方依赖log4net.dll版本1.2.9.0,项目中需要两种版本共存。
这里还分两种情况,DLL的publicKeyToken相同还是不同 (publicKeyToken查询见说明)

  • publicKeyToken相同,配置方法:
<runtime>
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <dependentAssembly>
      <assemblyIdentity name="log4net" publicKeyToken="669e0ddf0bb1aa2a" />
      <codeBase version="1.2.13.0" href="bin\log4netdll\1_2_13\log4net.dll" />
      <codeBase version="1.2.9.0" href="bin\log4netdll\1_2_9\log4net.dll" />
    </dependentAssembly>
  </assemblyBinding>
</runtime>
  • publicKeyToken不同,配置方法:
<runtime>
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <dependentAssembly>
      <assemblyIdentity name="log4net" publicKeyToken="669e0ddf0bb1aa2a" />
      <codeBase version="1.2.13.0" href="bin\log4netdll\1_2_13\log4net.dll" />
    </dependentAssembly>
    <dependentAssembly>
      <assemblyIdentity name="log4net" publicKeyToken="b32731d11ce58905" />
      <codeBase version="1.2.9.0" href="bin\log4netdll\1_2_9\log4net.dll" />
    </dependentAssembly>
  </assemblyBinding>
</runtime>

说明

  • publicKeyToken获取方式

使用Visual Studio的Tools Command Prompt命令行工具,输入:SN -T "path",例如:

C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC>SN -T D:\Newtonsoft.Json.dll

Microsoft(R) .NET Framework 强名称实用工具 版本 4.0.30319.33440
版权所有(C) Microsoft Corporation。保留所有权利。

公钥标记为 30ad4fe6b2a6aeed
posted @ 2019-04-08 20:41  大志若愚  阅读(21096)  评论(0编辑  收藏  举报