问题
I have this scenario, where I have the project's Assembly Version from AssemblyInfo.cs, for example 2.0.0 as below:
[assembly: AssemblyVersion("2.0.0")]
In addition, I would like to retrieve this AssemblyVersion and set it as part of the parameters in my web.config dynamically, such as below, for example:
<my.config.group>
<version versionNumber="2.0.0" />
</my.config.group>
I need to set the version number above, as the version number of my Assembly dynamically, to avoid having to modify it manually when something changes.
This is required because of how a third party library we are using works. Therefore, it is not possible to fetch the assembly version using an alternative way. We must stick to the web.config.
What is the neatest solution to achieve this? I was thinking of using a Powershell script Post-Build, however, I have little experience in Powershell so I wanted to know what is the best solution.
回答1:
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 present
if (-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.
来源:https://stackoverflow.com/questions/31938239/put-assembly-version-from-assemblyinfo-cs-in-web-config