For years, I used a PowerShell script to increment the PackageVersion
for my nuget library builds in Visual Studio. I found that annoying, so I began a quest to find a way to increment the version just using a Target/Task in the .NET Core *.csproj
project file.
1 Answer
After some time I eventually came across XmlPoke (thanks StackOverflow...) and so combined with using a MSBuild property function and a Target task - we can rock the version automagically
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<PackageId>MyAwesomePackage</PackageId>
<AssemblyName>MyAwesomePackage</AssemblyName>
<PackageVersion>1.0.1.1-Debug</PackageVersion>
<VersionPrefix>1.0.1</VersionPrefix>
<VersionSuffix>1</VersionSuffix>
<VersionSuffixBuild>$([MSBuild]::Add($(VersionSuffix),1))</VersionSuffixBuild>
<Authors>Me</Authors>
<Company>My Awesome Company</Company>
<Product>My Awesome Product</Product>
<Description>My Awesome Product Library</Description>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.Text.Json" Version="9.0.0" />
</ItemGroup>
<Target Name="UpdateVersion" AfterTargets="BeforeBuild">
<PropertyGroup>
<PackageVersion Condition="$(ConfigurationName) == Debug">$(VersionPrefix).$(VersionSuffixBuild)-Debug</PackageVersion>
<PackageVersion Condition="$(ConfigurationName) == Release">$(VersionPrefix).$(VersionSuffixBuild)</PackageVersion>
</PropertyGroup>
<Exec Condition="$(ConfigurationName) == Debug" Command="del /F "$(ProjectDir)bin\Debug\*.nupkg"" IgnoreExitCode="true" />
<Exec Condition="$(ConfigurationName) == Release" Command="del /F "$(ProjectDir)bin\Release\*.nupkg"" IgnoreExitCode="true" />
</Target>
<Target Name="PostBuild" AfterTargets="Pack">
<Exec Condition="$(ConfigurationName) == Debug" Command="nuget init "$(ProjectDir)\bin\Debug" "$(SolutionDir)..\packages\debug"" />
<Exec Condition="$(ConfigurationName) == Release" Command="nuget init "$(ProjectDir)\bin\Release" "$(SolutionDir)..\packages\release"" />
<XmlPoke XmlInputPath="$(MSBuildProjectFullPath)" Value="$(VersionSuffixBuild)" Query="/Project/PropertyGroup/VersionSuffix" />
<XmlPoke XmlInputPath="$(MSBuildProjectFullPath)" Value="$(PackageVersion)" Query="/Project/PropertyGroup/PackageVersion" />
</Target>
</Project>
-
1