.NET Framework 4.8控制台程序加载netstandard程序集失败求助
我有一个基于.NET Framework 4.8的旧控制台程序,它引用的若干NuGet包均支持.NET Standard 2.0和2.1。程序编译正常,但加载首个NuGet DLL时出现如下运行时错误:
System.IO.FileNotFoundException: Could not load file or assembly 'netstandard, Version=2.1.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The system cannot find the file specified.
File name: 'netstandard, Version=2.1.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' ---> System.IO.FileNotFoundException: Could not load file or assembly 'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The system cannot find the file specified.
File name: 'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'
从兼容性来看,.NET Framework 4.8本应兼容.NET Standard 2.0,请问无法加载netstandard 2.0或2.1的原因是什么?
[编辑补充]:控制台程序隐式依赖项截图
核心原因
-.NET Framework 4.8对.NET Standard 2.0的兼容并非原生内置,需要依赖NETStandard.Library.NETFramework兼容包提供netstandard程序集的实现,若未安装该包,运行时会找不到对应的程序集。
-.NET Framework 4.8不支持.NET Standard 2.1,如果引用的NuGet包依赖.NET Standard 2.1,CLR尝试加载该版本时会直接失败,进而触发链式错误(找不到2.1版本后回退查找2.0版本,若此时2.0的兼容实现也缺失,就会出现报错)。
-缺少正确的程序集绑定重定向配置,CLR无法将对不同版本netstandard的请求统一映射到兼容的版本,导致版本不匹配的加载错误。
-部分NuGet包的传递依赖中包含仅在.NET Core/.NET 5+环境下存在的组件,这些组件在.NET Framework 4.8中无法被解析,间接引发netstandard程序集的加载失败。
解决步骤
- 安装兼容包:给项目安装
NETStandard.Library.NETFrameworkNuGet包,确保运行时能获取到netstandard 2.0的兼容实现。 - 添加绑定重定向:在项目的
app.config中添加以下配置,将所有netstandard版本请求重定向到2.0.0.0版本:
<runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="netstandard" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-2.1.0.0" newVersion="2.0.0.0" /> </dependentAssembly> </assemblyBinding> </runtime>
- 调整NuGet包版本:检查所有引用的NuGet包,优先选择仅支持.NET Standard 2.0的版本,避免使用依赖.NET Standard 2.1的包(因为.NET Framework 4.8无法兼容2.1标准)。
- 清理并重新编译:删除项目的
bin和obj目录,重新编译项目,确保所有依赖文件被正确复制到输出目录。
内容的提问来源于stack exchange,提问作者Jonas Rembratt

