Search code examples
c#msbuildcsproj

Conditional properties in a C# project file


I use a Directory.Build.props file that has a certain group of properties that I want to include only if the project has GeneratePackageOnBuild set to true, or when the project is packaged.

This is for the latest version of .Net 7.

The example below does not appear to be working.

Directory.Build.props

<PropertyGroup Condition="'$(GeneratePackageOnBuild)' == 'true'">
    <PackageIcon>favicon.ico</PackageIcon>
    <PackageReadmeFile>README.md</PackageReadmeFile>
    <PublishRepositoryUrl>true</PublishRepositoryUrl>
    <EmbedUntrackedSources>true</EmbedUntrackedSources>
    <IncludeSymbols>true</IncludeSymbols>
    <SymbolPackageFormat>snupkg</SymbolPackageFormat>
</PropertyGroup>

Project.csproj

<Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup>
        <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
    </PropertyGroup>

Solution

  • The Directory.Build.props file is imported before the content of the project file. The GeneratePackageOnBuild property hasn't yet been set to true when the "'$(GeneratePackageOnBuild)' == 'true'" condition is evaluated.

    Move your PropertyGroup to the Directory.Build.targets file. The Directory.Build.targets file is imported after the content of the project file.

    Contrary to what the names may seem to imply, there are no special restrictions. Both the Directory.Build.props file and the Directory.Build.targets file can contain properties, items, and targets.

    In practice Directory.Build.props is hardly ever actually needed. Only when a property must be set before the project SDK (i.e. Sdk="Microsoft.NET.Sdk") logic is evaluated is there a need for the Directory.Build.props file. Everything else either can go or must go (because of dependencies) in the Directory.Build.targets file.