Put Assembly Version from AssemblyInfo.cs in Web.config Put Assembly Version from AssemblyInfo.cs in Web.config powershell powershell

Put Assembly Version from AssemblyInfo.cs in Web.config


Yes, you could do that using a post build event, but you can also do it as a deployment step or whatsoever.

The following script loads the assembly, reads the version information and formats a string. Then, it creates the version node on the config file if not present and sets the versionNumber attribute:

$assemblyFilePath = "C:\YourAssembly.dll"$configPath = "C:\YourWeb.config"# Retrieve the version$bytes = [System.IO.File]::ReadAllBytes($assemblyFilePath)$assembly = [System.Reflection.Assembly]::Load($bytes)$version = $assembly.GetName().Version;$versionString = [string]::Format("{0}.{1}.{2}",$version.Major, $version.Minor, $version.Build)$config = [xml](gc $configPath)$versionNode = $config.SelectSingleNode('configuration//version')# Ensure the version node is presentif (-not $versionNode){    $versionNode = $config.CreateElement('version')    $config.DocumentElement.AppendChild($versionNode)}# Set the version number attribute$versionNode.SetAttribute('versionNumber', $versionString)$config.Save($configPath)

You could also read and parse the AssemblyVersion attribute from the AssemblyInfo.cs. The reason why I prefer to load the assembly itselfs is because you can use this solution even if you only have the binaries.

And here an example how you can read the version from the AssemblyInfo.cs:

$assemblyInfoPath = "C:\AssemblyInfo.cs"$regex = '^\[assembly: AssemblyVersion\("(.*?)"\)\]'$assemblyInfo = Get-Content $assemblyInfoPath -Raw$version = [Regex]::Match(        $assemblyInfo,         $regex,        [System.Text.RegularExpressions.RegexOptions]::Multiline    ).Groups[1].Value

Now you can parse the version using [version]::Parse($version)and use the same format string as the example above.