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?
- Get the Current Date and Time: The
CurrentDateTime
property captures the current date and time usingSystem.DateTime::Now
. - Construct the Version Number: The
Version
property formats the date and time into a version string. The formatyyMM.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! 🚀