.NET 8自定义MSBuild任务加载失败:无法找到System.Runtime程序集
自定义MSBuild任务加载失败问题排查与解决
错误信息
MSB4062 The "HitcMacroTest.PreprocessTask" task could not be loaded from the assembly \bin\Debug\net8.0-windows\HitcMacroTest.dll. Could not load file or assembly 'System.Runtime, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified. Confirm that the <UsingTask> declaration is correct, that the assembly and all its dependencies are available, and that the task contains a public class that implements Microsoft.Build.Framework.ITask. WinFormsApp1 \Macro\WinFormsApp1\WinFormsApp1.csproj 28
项目环境
HitcMacroTest(自定义MSBuild任务项目)与WinFormsApp1(目标项目)均以**.NET 8.0**为目标框架,WinFormsApp1的csproj配置如下:
<ItemGroup> <PackageReference Include="Microsoft.Build.Utilities.Core" Version="17.10.4" /> </ItemGroup> <UsingTask TaskName="HitcMacroTest.PreprocessTask" AssemblyFile="F:\PROJECTS\Macro\WinFormsApp1\bin\Debug\net8.0-windows\HitcMacroTest.dll" /> <ItemGroup> <PreprocessSources Include="F:\PROJECTS\Macro\**\*.cs" Exclude="$(PreprocessedOutputDirectory)\**\*" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\HitcMacroTest\HitcMacroTest.csproj" /> </ItemGroup> <Target Name="PreprocessMacros" BeforeTargets="BeforeBuild"> <MakeDir Directories="$(PreprocessedOutputDirectory)" /> <PreprocessTask InputFiles="@(PreprocessSources)" OutputDirectory="$(PreprocessedOutputDirectory)" /> <ItemGroup> <Compile Remove="@(PreprocessSources)" /> <Compile Include="$(PreprocessedOutputDirectory)\**\*.cs" /> </ItemGroup> </Target>
解决方法
1. 修正程序集引用路径,确保构建顺序
当前AssemblyFile硬编码了WinFormsApp1的输出目录,但HitcMacroTest的程序集可能未被复制到该目录,或者路径存在问题。改用项目引用的输出路径变量,同时确保HitcMacroTest先于WinFormsApp1构建:
<!-- 替换原UsingTask节点 --> <UsingTask TaskName="HitcMacroTest.PreprocessTask" AssemblyFile="$(SolutionDir)HitcMacroTest\bin\$(Configuration)\net8.0\HitcMacroTest.dll" />
注:$(SolutionDir)为MSBuild内置变量,自动指向解决方案根目录,避免硬编码绝对路径。
2. 调整自定义任务项目的目标框架
MSBuild默认基于.NET Framework运行,直接加载.NET 8程序集可能出现依赖缺失。可将HitcMacroTest的目标框架改为**.NET Standard 2.0或.NET Framework 4.7.2**,同时匹配兼容版本的Microsoft.Build.Utilities.Core包:
- 修改HitcMacroTest.csproj的目标框架:
<TargetFramework>net472</TargetFramework> - 安装对应版本的NuGet包:
Microsoft.Build.Utilities.Core16.11.0(适配.NET Framework)
3. 使用.NET Core MSBuild构建
通过dotnet build命令构建项目,该命令使用.NET Core版本的MSBuild,能更好地兼容.NET 8程序集的依赖加载:
dotnet build WinFormsApp1.csproj -c Debug
4. 验证自定义任务类的实现
确保PreprocessTask是public类,且正确实现ITask接口(继承Microsoft.Build.Utilities.Task更简便):
using Microsoft.Build.Utilities; using Microsoft.Build.Framework; public class PreprocessTask : Task { [Required] public ITaskItem[] InputFiles { get; set; } [Required] public string OutputDirectory { get; set; } public override bool Execute() { // 任务逻辑实现 return true; } }
5. 确保依赖库复制到输出目录
在HitcMacroTest项目中,设置所有NuGet依赖的CopyLocal为true,确保依赖库被复制到输出目录,供MSBuild加载时使用。
内容的提问来源于stack exchange,提问作者pramod maurya
相关产品推荐
相关产品推荐

