Automatically update .NET Core assembly version on build


Summary

In programming, it is often desirable to assign a meaningful version number to an assembly. A common format involves using a timestamped version, specifically in the format YYYY.MM.DD.SSSSS, which represents the year, month, day, and seconds since midnight. To automate the incrementation of this version number, the csproj file can be updated with the following pre-build event:

  <Target Name="UpdateVersion" BeforeTargets="BeforeBuild">
    <PropertyGroup>
      <!-- Get the current date and time -->
      <CurrentDateTime>$([System.DateTime]::Now)</CurrentDateTime>

      <!-- Extract the year, month, day -->
      <Year>$([System.DateTime]::Parse($(CurrentDateTime)).ToString("yyyy"))</Year>
      <Month>$([System.DateTime]::Parse($(CurrentDateTime)).ToString("MM"))</Month>
      <Day>$([System.DateTime]::Parse($(CurrentDateTime)).ToString("dd"))</Day>

      <!-- Calculate seconds since midnight -->
      <SecondsSinceMidnight>$([System.DateTime]::Parse($(CurrentDateTime)).TimeOfDay.TotalSeconds.ToString("00000"))</SecondsSinceMidnight>

      <!-- Construct the version number -->
      <Version>$(Year).$(Month).$(Day).$(SecondsSinceMidnight)</Version>
    </PropertyGroup>
  </Target>

Note: The version number will not be visible in the XML of the csproj file itself, but it will be applied to the assembly during the build process. To verify this, right-click on the generated DLL or EXE file in Windows Explorer, select "Properties," and you will see the timestamped version number.