You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core项目如何在每次发布构建时自动递增版本号?

.NET Core/.NET 5+ 构建时自动递增版本号的方法

在.NET Core及后续版本中,AssemblyInfo.cs默认由MSBuild自动生成,版本信息直接通过项目文件(.csproj)管理。以下是几种实现每次发布构建时自动递增版本号(如1.0.0.1 → 1.0.0.2)的实用方案:

方案1:通过脚本修改.csproj中的Version属性

  1. 在.csproj中配置基础版本
    打开项目文件,添加或修改Version属性:

    <PropertyGroup>
      <!-- 初始版本号 -->
      <Version>1.0.0.0</Version>
    </PropertyGroup>
    
  2. 编写版本递增脚本
    新建PowerShell脚本(如IncrementVersion.ps1),读取并递增版本号最后一位:

    # 替换为你的项目文件路径
    $csprojPath = ".\YourProject.csproj"
    $xml = [xml](Get-Content $csprojPath)
    $versionNode = $xml.Project.PropertyGroup.Version
    
    if ($versionNode) {
        $versionParts = $versionNode.Split('.')
        # 递增修订号(最后一位)
        $versionParts[3] = [int]$versionParts[3] + 1
        $newVersion = $versionParts -join '.'
        $xml.Project.PropertyGroup.Version = $newVersion
        $xml.Save($csprojPath)
        Write-Host "版本已更新为: $newVersion"
    }
    
  3. 绑定到构建流程

    • 如果用Visual Studio:右键项目 → 属性 → 生成事件 → 预生成事件命令行,添加:
      powershell -ExecutionPolicy Bypass -File "$(SolutionDir)IncrementVersion.ps1"
      
    • 如果用命令行构建:先执行脚本再运行dotnet build/dotnet publish:
      powershell -ExecutionPolicy Bypass -File IncrementVersion.ps1
      dotnet publish -c Release
      

方案2:通过外部文件存储版本号

如果不想直接修改.csproj,可以用单独的文件存储版本,在构建时读取:

  1. 创建Version.txt文件
    在项目根目录新建Version.txt,写入初始版本:

    1.0.0.0
    
  2. 在.csproj中读取版本文件
    修改项目文件,从Version.txt读取版本号:

    <PropertyGroup>
      <Version>$([System.IO.File]::ReadAllText('Version.txt').Trim())</Version>
    </PropertyGroup>
    
  3. 修改脚本读取并更新Version.txt
    调整PowerShell脚本(IncrementVersion.ps1):

    $versionFile = ".\Version.txt"
    $currentVersion = Get-Content $versionFile -Raw | Trim
    $versionParts = $currentVersion.Split('.')
    $versionParts[3] = [int]$versionParts[3] + 1
    $newVersion = $versionParts -join '.'
    Set-Content $versionFile $newVersion
    Write-Host "版本已更新为: $newVersion"
    

    后续构建流程和方案1一致,先执行脚本再构建。

方案3:禁用自动生成AssemblyInfo,沿用.NET Framework方式

如果习惯手动维护AssemblyInfo.cs,可以禁用自动生成:

  1. 在.csproj中关闭自动生成

    <PropertyGroup>
      <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
    </PropertyGroup>
    
  2. 手动添加AssemblyInfo.cs
    在项目中新建Properties/AssemblyInfo.cs文件,添加版本属性:

    using System.Reflection;
    
    [assembly: AssemblyVersion("1.0.0.0")]
    [assembly: AssemblyFileVersion("1.0.0.0")]
    
  3. 用原有的修改脚本更新该文件
    你之前在.NET Framework中使用的修改AssemblyInfo.cs的脚本,稍作调整即可在.NET Core项目中使用。

注意:如果使用CI/CD工具(如GitHub Actions、Azure DevOps),可以直接在流水线中集成版本递增逻辑,无需本地脚本,比如利用流水线的构建号来自动生成版本号。

内容的提问来源于stack exchange,提问作者Dan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 10:42:36