C# Winform 软件版本号自动增加

目录

一、简介

二、方式一

1.新建文件 version.txt

2.新建文件 UpdateVersion.ps1

3.修改 .csproj 文件

二、方式二

1.新建文件 UpdateVersion.ps1

2.添加“生成后事件命令行”

结束


 

 

一、简介

在平时的开发中,版本号的是常用的功能,除非你的程序不经常更新,光看软件的界面不可能就知道代码具体改了什么。在 C# 的开发中,很多程序员依然是手动的去改版本号,但非常的麻烦,每次生成前必须去 AssemblyInfo.cs 这个类中修改,但不排除部分公司压根不用软件版本号这个功能,我以前就遇到过,虽然他们不用,但也不影响软件的正常运行,不管怎样,版本号的管理加上去还是好的。

版本号主要分为4个部分,如 1.0.0.0,分别是 主版本.次版本.构建号.修订号。

我想定义的规则:

比如第四位满 99,就让第三位+1,第三位满99,就 让第二位+1,比如:

旧版本 递增后 解释
1.0.0.99 1.0.1.0 修订号 进位
1.0.99.99 1.1.0.0 修订号 & 构建号 进位
1.99.99.99 2.0.0.0 修订号 & 构建号 & 次版本号 全部进位
99.99.99.99 100.0.0.0 主版本号 进位

 

 

 

 

 

 

目前这套实现方式,就是根据这个规则来实现的,如果你想用其他的规则,需要自己修改。

下面的两个实现方式中,方式一比较麻烦,不推荐,方式二的实现比较简单,不用修改项目的配置文件,用起来也方便,推荐!

 

二、方式一

使用 version.txt 和 AssemblyInfo.cs 两个文件,他们的作用如下:

1.保持“版本状态”

version.txt 作为一个“存储文件”,让每次构建都能基于上一次的版本号递增。
这样即使你关闭 Visual Studio 或者换台电脑,版本号还是可以从上次的版本继续增加,而不会因为 AssemblyInfo.cs 被编译后“丢失状态”。


2.构建时的版本读取

csproj 读取 version.txt,然后传递给 UpdateVersion.ps1,这样 PowerShell 不会从零开始,而是从已有的版本继续递增。
PowerShell 先更新 AssemblyInfo.cs,然后 再更新 version.txt,保证下次构建继续递增。

 

1.新建文件 version.txt

位置在项目的根目录,如图:

 

在 version.txt 里面填写一个版本号:

1.0.0.0

 

2.新建文件 UpdateVersion.ps1

位置在根目录,可以参考上面步骤1中的图片,内容如下:

param(
    [string]$currentVersion,
    [string]$filePath
)

# 获取 version.txt 的路径
$versionFile = "$PSScriptRoot\version.txt"

# 解析版本号
$parts = $currentVersion -split "\."
$major = [int]$parts[0]
$minor = [int]$parts[1]
$build = [int]$parts[2]
$revision = [int]$parts[3]

# 版本号递增逻辑
$revision++
if ($revision -ge 100) {
    $revision = 0
    $build++
    
    if ($build -ge 100) {
        $build = 0
        $minor++
        
        if ($minor -ge 100) {
            $minor = 0
            $major++
        }
    }
}

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

# 更新 AssemblyInfo.cs
$content = Get-Content $filePath
$content = $content -replace '\[assembly: AssemblyVersion\(".*?"\)\]', "[assembly: AssemblyVersion(`"$newVersion`")]"
$content = $content -replace '\[assembly: AssemblyFileVersion\(".*?"\)\]', "[assembly: AssemblyFileVersion(`"$newVersion`")]"
Set-Content -Path $filePath -Value $content

# 更新 version.txt
Set-Content -Path $versionFile -Value $newVersion

Write-Output $newVersion

 

3.修改 .csproj 文件

这个是项目的配置文件,打开后,在标签的最后添加下面的代码:

<Target Name="UpdateAssemblyVersion" BeforeTargets="BeforeBuild">
    <PropertyGroup>
        <VersionFile>$(ProjectDir)version.txt</VersionFile>
        <AssemblyInfoFile>$(ProjectDir)Properties\AssemblyInfo.cs</AssemblyInfoFile>
    </PropertyGroup>

    <ReadLinesFromFile File="$(VersionFile)">
        <Output TaskParameter="Lines" PropertyName="NewVersion" />
    </ReadLinesFromFile>

    <Message Text="Updating AssemblyInfo.cs with version $(NewVersion)" Importance="high" />

    <Exec Command="powershell -ExecutionPolicy Bypass -NoProfile -File &quot;$(ProjectDir)UpdateVersion.ps1&quot; &quot;$(NewVersion)&quot; &quot;$(AssemblyInfoFile)&quot;" />
</Target>

在生成项目后,或者重新生成后,版本号就会自动的+1,如图:

 

同时 version.txt 里的版本号也会自动增加

打开项目的 AssemblyInfo.cs 文件,你会发现这里也自动更改了,如下:

 

二、方式二

在方式一中,必须要手动的建一个文件 version.txt,这是因为 AssemblyInfo.cs 文件有时候在项目迁移过程中,可能会丢失,或者多人合作,导致版本号异常,如果你是单人,也可以直接修改 AssemblyInfo.cs 来让版本号自动增加

对比方式一,方法二的实现就非常的简单了,这个是我比较喜欢的方式。

 

 

 

1.新建文件 UpdateVersion.ps1

位置在项目的根目录,内容如下:

# 获取当前脚本所在的项目根目录
$projectPath = Split-Path -Parent $MyInvocation.MyCommand.Path
$assemblyInfoPath = "$projectPath\Properties\AssemblyInfo.cs"

# 检查文件是否存在
if (-Not (Test-Path $assemblyInfoPath)) {
    Write-Output "Error: AssemblyInfo.cs not found at $assemblyInfoPath"
    exit 1
}

# 读取文件内容
$content = Get-Content $assemblyInfoPath -Raw

# 匹配版本号
$pattern = '\[assembly: AssemblyVersion\("(\d+)\.(\d+)\.(\d+)\.(\d+)"\)\]'

if ($content -match $pattern) {
    $major = [int]$matches[1]
    $minor = [int]$matches[2]
    $build = [int]$matches[3]
    $revision = [int]$matches[4]

    # 版本号递增逻辑
    $revision++
    if ($revision -ge 100) {
        $revision = 0
        $build++
    }
    if ($build -ge 100) {
        $build = 0
        $minor++
    }
    if ($minor -ge 100) {
        $minor = 0
        $major++
    }

    # 生成新的版本号
    $newVersion = "$major.$minor.$build.$revision"

    # 替换 AssemblyInfo.cs 中的版本号
    $newContent = $content -replace $pattern, "[assembly: AssemblyVersion(`"$newVersion`")]"
    $newContent = $newContent -replace '\[assembly: AssemblyFileVersion\("(\d+)\.(\d+)\.(\d+)\.(\d+)"\)\]', "[assembly: AssemblyFileVersion(`"$newVersion`")]"

    # 写回文件
    Set-Content -Path $assemblyInfoPath -Value $newContent -Encoding UTF8

    Write-Output "Updated version to $newVersion"
} else {
    Write-Output "AssemblyVersion not found in $assemblyInfoPath!"
}

位置:

 

2.添加“生成后事件命令行”

打开项目,在 项目的属性 --> 生成事件 --> 生成后事件命令行 输入了提供的命令,就能完成这个需求

命令:

powershell -ExecutionPolicy Bypass -File "$(ProjectDir)UpdateVersion.ps1"

效果:

 

每次生成,或者重新生成后,这里都会自动+1。

如果你想读取这些版本号,可以这么做:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Test5
{
    public partial class Form1: Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Console.WriteLine("程序集版本号:{0}", GetAssemblyVersion());
            Console.WriteLine("程序集文件版本号:{0}", AssemblyFileVersion());
        }

        /// <summary>
        /// 读取程序集版本号
        /// </summary>
        /// <returns></returns>
        private string GetAssemblyVersion()
        {
            var assembly = Assembly.GetExecutingAssembly();
            return assembly?.GetName().Version?.ToString();
        }

        /// <summary>
        /// 读取程序集文件版本号
        /// </summary>
        /// <returns></returns>
        private string AssemblyFileVersion()
        {
            object[] attributes = Assembly.GetExecutingAssembly()
                .GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false);
            if (attributes.Length != 0)
                return ((AssemblyFileVersionAttribute)attributes[0]).Version;
            else
                return string.Empty;
        }
    }
}

运行:

 

 

 

 

 

结束

如果这个帖子对你有所帮助,欢迎 关注 + 点赞 + 留言

end

posted @ 2025-05-10 12:43  野狼谷  阅读(356)  评论(0)    收藏  举报