VS 在编译和发布时自动修改版本号(DotNet Framework)
1.在项目根目录下添加 PowerShell 脚本文件,脚本文件名称随意,例如:Pre-Build.ps1;脚本中输入参数 $projectDir 为项目路径,$configurationName 为配置名称 Debug 或者 Release,版本号规则,主版本号不变,请自行调整,第二位仅在 Release 时变更,第三位为日期:一位年两位月份两位日期(20205-01-01 为 50101),第四位在 Debug 或者 Release 发布时自动递增,如果对版本要求不是很严格的话基本够用。脚本代码如下:
param(
[string]$projectDir,
[string]$configurationName
)
$versionFilePath = $projectDir + "Properties\AssemblyInfo.cs"
$versionFileContent = Get-Content $versionFilePath
$versionMatch = Select-String -Path $versionFilePath -Pattern "AssemblyVersion\(`"(\d+\.\d+\.\d+\.\d+)`"\)"
$currentVersion = $versionMatch.Matches.Groups[1].Value
$versionParts = $currentVersion.Split('.')
if ($configurationName -eq "Release")
{
$versionParts[1] = [int]$versionParts[1] + 1
}
$versionParts[2] = (Get-Date -Format 'yyyyMMdd').substring(3)
$versionParts[3] = [int]$versionParts[3] + 1
$newVersion = $versionParts -join '.'
$newVersionContent = "AssemblyVersion(`"$newVersion`")"
$oldVersionContent = $versionMatch.Matches.Value -replace "\(", "\("
$oldVersionContent = $oldVersionContent -replace "\)", "\)"
$versionFileContent = $versionFileContent -replace $oldVersionContent, $newVersionContent
Set-Content -Path $versionFilePath -Value $versionFileContent
2.打开项目属性,在“生成事件”标签中“生成前事件命令行”中填写如下:
powershell -ExecutionPolicy RemoteSigned -Command "&'$(ProjectDir)Pre-Build.ps1' '$(ProjectDir)' '$(ConfigurationName)'"


浙公网安备 33010602011771号