Reputation: 3190
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.
Upvotes: 2
Views: 2104
Reputation: 10350
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.
Upvotes: 1
Reputation: 2135
It seems like it is not possible to do it inside VersionInfo.cs
itself. Even though it is possible to pass special symbols to C# compiler (see also MSDN Article about this), they cannot hold a value, unlike C/C++ symbols.
However, it is certainly possible to generate VersionInfo.cs
algorithmically with, for example, another simple C# program. Firstly, write a program that modifies VersionInfo.cs
with information obtained from another source, probably from Environment.GetEnvironmentVariable
method invocation. Then add a pre-build command to the build of your project, see an MSDN article for details on how to do it. At pre-build event, call your program so that it will update VersionInfo.cs
before the compiler is invoked.
Upvotes: 1