如何用dotnet build命令将多个项目编译至同一输出目录?
解决dotnet build多项目编译报错的方法
dotnet build命令本身不支持直接传入多个.csproj文件作为参数,这就是你遇到MSB1008错误的原因。以下是几种可行的解决方案,无需编译整个解决方案:
方法1:循环执行单项目编译命令
通过批处理或Shell脚本,逐个调用dotnet build命令,为每个项目指定相同的输出目录:
Windows CMD脚本
@echo off set "OUTPUT_DIR=.\bin\Debug\win-x64\shared" dotnet build MyProj\MyProj.csproj --configuration Debug -r win-x64 -p:Platform=x64 -p:OutputPath=%OUTPUT_DIR% dotnet build MyProj2\MyProj2.csproj --configuration Debug -r win-x64 -p:Platform=x64 -p:OutputPath=%OUTPUT_DIR%
Linux/macOS Bash脚本
OUTPUT_DIR="./bin/Debug/win-x64/shared" dotnet build MyProj/MyProj.csproj --configuration Debug -r win-x64 -p:Platform=x64 -p:OutputPath="$OUTPUT_DIR" dotnet build MyProj2/MyProj2.csproj --configuration Debug -r win-x64 -p:Platform=x64 -p:OutputPath="$OUTPUT_DIR"
方法2:创建临时解决方案文件
生成一个只包含目标项目的临时解决方案,再编译这个方案:
# 创建临时解决方案 dotnet new sln -n TempBuildSln # 添加需要编译的项目到临时方案 dotnet sln TempBuildSln.sln add MyProj\MyProj.csproj MyProj2\MyProj2.csproj # 编译临时方案,指定输出目录 dotnet build TempBuildSln.sln --configuration Debug -r win-x64 -p:Platform=x64 -p:OutputPath=.\bin\Debug\win-x64\shared # 编译完成后可删除临时sln文件 del TempBuildSln.sln
方法3:创建包装项目
新建一个空的"包装"项目,引用所有需要编译的目标项目,编译这个包装项目即可一次性完成所有目标项目的编译:
- 创建名为
BuildWrapper.csproj的文件,内容如下(注意匹配你的项目目标框架):
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net6.0</TargetFramework> <OutputType>Exe</OutputType> <Configuration>Debug</Configuration> <RuntimeIdentifier>win-x64</RuntimeIdentifier> <Platform>x64</Platform> <OutputPath>./bin/Debug/win-x64/shared</OutputPath> </PropertyGroup> <ItemGroup> <ProjectReference Include="MyProj\MyProj.csproj" /> <ProjectReference Include="MyProj2\MyProj2.csproj" /> </ItemGroup> </Project>
- 执行编译命令:
dotnet build BuildWrapper.csproj
内容的提问来源于stack exchange,提问作者jasper
相关产品推荐
相关产品推荐

