.NET 7 C#项目自动生成year.month.build格式版本号的问题
.NET 7 自动生成 year.month.build 格式版本号方案
针对你需要自动生成年.月.构建号格式版本号的需求,这里提供两种实用方案,解决你之前遇到的*占位符失效、年月手动修改的问题:
方案一:用当年累计天数作为构建号(无修订号)
这个方案直接通过MSBuild计算生成符合要求的版本号,完全自动无需手动干预:
- 在项目的
.csproj文件中添加以下配置:
<PropertyGroup> <!-- 关闭自动生成AssemblyInfo,避免冲突 --> <GenerateAssemblyInfo>false</GenerateAssemblyInfo> <!-- 获取当前UTC时间的年、月 --> <CurrentYear>$([System.DateTime]::UtcNow.Year)</CurrentYear> <CurrentMonth>$([System.DateTime]::UtcNow.ToString("MM"))</CurrentMonth> <!-- 计算当年1月1日到当前日期的天数,作为构建号 --> <DaysSinceYearStart>$([System.DateTime]::Subtract($([System.DateTime]::UtcNow), $([System.DateTime]::new($([System.DateTime]::UtcNow.Year), 1, 1))).Days)</DaysSinceYearStart> <!-- 拼接最终版本号,格式为 year.month.build --> <AssemblyVersion>$(CurrentYear).$(CurrentMonth).$(DaysSinceYearStart)</AssemblyVersion> <FileVersion>$(AssemblyVersion)</FileVersion> </PropertyGroup>
- 保存后重新构建项目,生成的版本号会自动变为
2024.05.123这类格式(123是当年第123天)。
- 如果需要用本地时间而非UTC,把所有
UtcNow替换为Now即可。 - 若在CI/CD环境中,可以把
DaysSinceYearStart替换为CI的构建编号(比如GitHub Actions的GITHUB_RUN_NUMBER),确保构建号全局唯一递增。
方案二:利用.NET自动构建号机制(兼容*占位符)
如果你想保留.NET自动生成当日构建次数的逻辑,同时自动填充年月,可以通过MSBuild动态生成AssemblyVersion属性:
在.csproj文件中添加:
<PropertyGroup> <GenerateAssemblyInfo>false</GenerateAssemblyInfo> <!-- 自动获取年月 --> <AutoVersionYear>$([System.DateTime]::UtcNow.Year)</AutoVersionYear> <AutoVersionMonth>$([System.DateTime]::UtcNow.ToString("MM"))</AutoVersionMonth> </PropertyGroup> <ItemGroup> <!-- 动态生成AssemblyVersion属性,*会自动生成当日构建号和修订号 --> <AssemblyAttribute Include="System.Reflection.AssemblyVersion"> <Value>$(AutoVersionYear).$(AutoVersionMonth).*</Value> </AssemblyAttribute> <!-- 若要去掉修订号,可设置为固定0 --> <AssemblyAttribute Include="System.Reflection.AssemblyFileVersion"> <Value>$(AutoVersionYear).$(AutoVersionMonth).$(BuildNumber).0</Value> </AssemblyAttribute> </ItemGroup>
注:此方案中*会生成build.revision格式的后两位,其中build是当日的构建次数(从0开始),revision是当日的秒数除以2。如果不需要修订号,建议用方案一更贴合需求。
内容的提问来源于stack exchange,提问作者ba19
相关产品推荐
相关产品推荐

