How to Auto Increment the Version Number of a C# .NET Assembly

Managing version numbers in a C# applications can be a hassle, especially if you want them to increment automatically with each publish. Here’s a simple solution to automate this process using MSBuild.

The Solution

Add the following code to your project file (.csproj):


<Target Name="UpdateVersion" BeforeTargets="BeforeBuild">
<PropertyGroup>

<!-- Get the current date and time -->
<CurrentDateTime>$([System.DateTime]::Now)</CurrentDateTime>

<!-- Construct the version number -->
<Version>1.0.$([System.DateTime]::Parse($(CurrentDateTime)).ToString("yyMM.ddHH"))</Version>
</PropertyGroup>
</Target>

What’s Happening Here?

  1. Get the Current Date and Time: The CurrentDateTime property captures the current date and time using System.DateTime::Now.
  2. Construct the Version Number: The Version property formats the date and time into a version string. The format yyMM.ddHH ensures the version number includes the year, month, day, and hour, making it unique for each build.

This approach ensures your version number increments automatically with each build, saving you from manual updates.

Happy coding! 🚀