Search code examples
c#environment-variablesversion-numbering

c# assign version number via Environment Variable


I currently have a VersionInfo.cs file that contains the following.

using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

//Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Version
//      Revision
//
//You can specify all the values or you can defaul the Revision and Build Numbers
//by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

This file is added as a link to all the projects in my solution, so updating the version number in one, updates all of it. This works fine.

But I'm wondering is it possible to retrieve version number from an environment variable and then use that in the VersionInfo.cs file?. Can this be done in the VersionInfo.cs file itself?.

I searched for something like this and so far got nothing.


Solution

  • Here is a PowerShell script that updates AssemblyVersion and AssemblyFileVersion based on a environment variable called BUILD_NUMBER.

    if (Test-Path env:BUILD_NUMBER) {
        Write-Host "Updating AssemblyVersion to $env:BUILD_NUMBER"
    
        # Get the AssemblyInfo.cs
        $assemblyInfo = Get-Content -Path .\MyShinyApplication\Properties\AssemblyInfo.cs
    
        # Replace last digit of AssemblyVersion
        $assemblyInfo = $assemblyInfo -replace 
            "^\[assembly: AssemblyVersion\(`"([0-9]+)\.([0-9]+)\.([0-9]+)\.[0-9]+`"\)]", 
            ('[assembly: AssemblyVersion("$1.$2.$3.' + $env:BUILD_NUMBER + '")]')
        Write-Host  ($assemblyInfo -match '^\[assembly: AssemblyVersion')
            
        # Replace last digit of AssemblyFileVersion
        $assemblyInfo = $assemblyInfo -replace 
            "^\[assembly: AssemblyFileVersion\(`"([0-9]+)\.([0-9]+)\.([0-9]+)\.[0-9]+`"\)]", 
            ('[assembly: AssemblyFileVersion("$1.$2.$3.' + $env:BUILD_NUMBER + '")]')
        Write-Host  ($assemblyInfo -match '^\[assembly: AssemblyFileVersion')
            
        $assemblyInfo | Set-Content -Path .\MyShinyApplication\Properties\AssemblyInfo.cs -Encoding UTF8
    } else {
        Write-Warning "BUILD_NUMBER is not set."
    }
    

    Call this script from a pre-build step on your build system.