C#类库项目中实现版本号每次编译时自动增加

在C#类库项目中实现版本号每次编译时自动增加,可以使用MSBuild的目标或脚本来更新版本号。下面提供一个详细的方法,使用MSBuild脚本在每次编译时更新版本号。

方法:使用MSBuild任务更新版本号

1. 修改项目文件(.csproj)

首先,打开你的C#类库项目文件(.csproj),添加以下内容以使用MSBuild任务在编译前自动更新版本号。

复制代码

xml

复制代码

<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net5.0</TargetFramework> <!-- 默认版本号 --> <Version>1.0.0.0</Version> <FileVersion>1.0.0.0</FileVersion> <AssemblyVersion>1.0.0.0</AssemblyVersion> </PropertyGroup> <ItemGroup> <None Update="Version.txt"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> </ItemGroup> <Target Name="IncrementVersion" BeforeTargets="BeforeBuild"> <Exec Command="powershell -ExecutionPolicy Bypass -File UpdateVersion.ps1" /> </Target> </Project>

2. 创建版本号文件

在项目根目录下创建一个名为Version.txt的文件,初始内容如下:

1.0.0.0

3. 编写PowerShell脚本

在项目根目录下创建一个名为UpdateVersion.ps1的PowerShell脚本,用于更新版本号。脚本内容如下:

$versionFilePath = "Version.txt"

读取当前版本号

currentVersion = Get-Content versionFilePath

拆分版本号

versionParts = currentVersion -split '\.'

major = \[int\]versionParts0

minor = \[int\]versionParts1

build = \[int\]versionParts2

revision = \[int\]versionParts3

递增修订号

$revision++

更新版本号

newVersion = "major.minor.build.$revision"

将新版本号写入Version.txt

Set-Content versionFilePath newVersion

更新项目文件中的版本号属性

$projectFilePath = "YourProjectName.csproj" # 请将此行替换为你的实际项目文件名

projectFileContent = Get-Content projectFilePath

updatedProjectFileContent = projectFileContent -replace '<Version>.*<\/Version>', "<Version>$newVersion</Version>"

updatedProjectFileContent = updatedProjectFileContent -replace '<FileVersion>.*<\/FileVersion>', "<FileVersion>$newVersion</FileVersion>"

updatedProjectFileContent = updatedProjectFileContent -replace '<AssemblyVersion>.*<\/AssemblyVersion>', "<AssemblyVersion>$newVersion</AssemblyVersion>"

Set-Content projectFilePath updatedProjectFileContent

请注意,将脚本中的YourProjectName.csproj替换为实际的项目文件名。

整体流程解释:

  1. 项目文件(.csproj)修改:

    • 配置了版本号属性(Version、FileVersion、AssemblyVersion)。
    • 添加了一个MSBuild目标IncrementVersion,在每次编译前运行PowerShell脚本。
  2. Version.txt文件:

    • 存储当前的版本号。
    • 初始内容为1.0.0.0。
  3. PowerShell脚本(UpdateVersion.ps1):

    • 读取并解析当前版本号。
    • 递增修订号。
    • 更新Version.txt文件中的版本号。
    • 更新项目文件中的版本号属性。

这种方法通过每次编译前运行一个PowerShell脚本来自动递增版本号,实现了版本号的自动管理。

相关推荐
data analyse 45616 分钟前
埋点工具的埋点查询语言难学吗?
前端·数据分析
DianSan_ERP25 分钟前
多平台订单自动下载与回传的技术实现:从消息推送到状态闭环引言
java·linux·服务器·前端·网络·架构·自动化
恋猫de小郭25 分钟前
Shopify 回应为什么从 RN 回到原生,为什么不用 KMP ?
android·前端·flutter
小蜗 strong1 小时前
和电脑猜拳(随机程序应用)
服务器·前端·python
下家2 小时前
为了脱离前端鄙视链,于是自己写个框架 - React 党看完沉默了
前端·前端框架
zhiyouTech2 小时前
从“被看见“到“被信任“:关于信源评级机制的一点观察
大数据·前端·人工智能
Hashan2 小时前
Vibe Coding 下前后端怎么对接接口?后端不给力的兜底方案
前端·后端·vibecoding
你挚爱的强哥3 小时前
【sgKeyboard】自定义组件:虚拟键盘
前端·javascript·计算机外设
锅里游的鱼吖3 小时前
echarts自定义折线图
前端·javascript·数据库
hunteritself4 小时前
卷卷卷!GPT-6 Sol、Luna 正式发布,OpenAI 开始卷价格了
大数据·前端·人工智能·深度学习·transformer