I have the following Directory.build.targets
file located next to the solution file:
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<BinaryFormats Include="$(SolutionDir)Projects\BinaryFormats\bin\Debug\netstandard2.1\BinaryFormats.dll" />
<BinaryFormats Include="$(SolutionDir)Projects\BinaryFormats\bin\Debug\netstandard2.1\BinaryFormats.pdb" />
</ItemGroup>
<Target Name="CopyUnityPlugins" AfterTargets="Build">
<Copy SourceFiles="@(BinaryFormats)" DestinationFolder="$(SolutionDir)Assets\Plugins" />
</Target>
</Project>
Its job is to copy some class libraries to $(SolutionDir)Assets\Plugins
and achieves in doing so.
One thing however, each of the file path to be copied is hard-coded.
Question:
Is it possible somehow to imports the macros of a .csproj and use them in the file?
For instance, to be able to use the following syntax instead of hard-coded paths:
<ItemGroup>
<BinaryFormats Include="$(TargetDir)$(TargetName).dll"/>
<BinaryFormats Include="$(TargetDir)$(TargetName).pdb"/>
</ItemGroup>
CodePudding user response:
Yes, that works. The Directory.build.props
and Directory.build.targets
files are evaluated respectively executed for each project separately. For each project, the corresponding macros (such as $(TargetPath)
or $(ProjectPath)
) will have the values for that particular project. So your above example <BinaryFormats Include="$(TargetDir)$(TargetName).pdb"/>
should just work as written.
With additional conditions, you can also use these files to conditionally extend your projects. For instance, I have a large solution (100 projects) where the Directory.build.props
contains this section:
<ItemGroup Condition="($(MSBuildProjectName.EndsWith('UnitTest')) OR $(MSBuildProjectName.EndsWith('IntegrationTest'))) AND '$(MSBuildProjectExtension)' == '.csproj'">
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.10.0" />
<PackageReference Include="NUnit3TestAdapter" Version="4.0.0" />
</ItemGroup>
This automatically adds these two packages as references to all unit test projects (and only these), which not only reduces clutter on the project files themselves but also allows me to upgrade these packages with only changing a single line of code.