A Simple Auto-Incrementing Version Number for C#
There are many solutions out there, but for posterity's sake (read: I am forgetful which link I used last time) I will record the easiest to implement and manage here. Maybe it will help someone (besides myself).
This will simply take the current date and push it into the version
field of the project whenever you hit Publish. It does so in an always-incrementing way, which is incredibly helpful and really what you want. It also does so in a relatively readable way, as the version number is always YYYY.DDD.HH.MM, where Y is the year (2020), D is the day of the year (0..364), H is the hour of the day (0..23), and M is the minute of the hour (0..59). This is handy because it properly sorts, but also tells you exactly when it was built, even if the file gets copied around a bit and the file date gets smashed.
How do you do it? Very simple. Just open each .csproj you want to have this versioning scheme and paste it into the <PropertyGroup>
at the top of the file that contains your Platforms
and Copyright
tags. It works for assemblies or executables, and you will notice Visual Studio evaluates it whenever you open the .sln and whenever you hit Publish.
<VersionSuffix>$([System.DateTime]::UtcNow.Year.ToString()).$([System.DateTime]::UtcNow.DayOfYear.ToString()).$([System.DateTime]::UtcNow.Hour.ToString()).$([System.DateTime]::UtcNow.Minute.ToString())</VersionSuffix>
<AssemblyVersion>$(VersionSuffix)</AssemblyVersion>
<Version>$(VersionSuffix)</Version>
Drawbacks? Several. But they may be fine for your purposes.
- Can't express major/minor/breaking changes. It's just an incrementing number, that's all. You could certainly change the scheme to have a manually set value at the front if you need one and change the HH.MM field to just be minutes since midnight.
- Can't disambiguate between multiple builds in a minute. I figure this is fine, unless you're iterating really fast (read: you have no idea what you're doing wrong--haha!). Change MM to seconds since the hour if you have a real problem with it.
Anyway, this is a useful snippet for me, so I thought I'd share.