[Visual Studio 2017, .csproj 属性]
要自动更新 PackageVersion/Version/AssemblyVersion 属性(或任何其他属性),首先,创建一个新的 Microsoft.Build.Utilities.Task
类,该类将获取当前的构建号并返回更新后的数字(我建议为该类创建单独的项目)。
我手动更新主版本和次版本号,但让 MSBuild 自动更新构建号(1.1.1,1.1.2,1.1.3 等等 :)。
using Microsoft.Build.Framework;
using System;
using System.Collections.Generic;
using System.Text;
public class RefreshVersion : Microsoft.Build.Utilities.Task
{
[Output]
public string NewVersionString { get; set; }
public string CurrentVersionString { get; set; }
public override bool Execute()
{
Version currentVersion = new Version(CurrentVersionString ?? "1.0.0");
DateTime d = DateTime.Now;
NewVersionString = new Version(currentVersion.Major,
currentVersion.Minor, currentVersion.Build+1).ToString();
return true;
}
}
然后在你的 .csproj 文件中添加以下代码,调用最近创建的 Task 并运行 MSBuild 进程:
<Project Sdk="Microsoft.NET.Sdk">
...
<UsingTask TaskName="RefreshVersion" AssemblyFile="$(MSBuildThisFileFullPath)\..\..\<dll path>\BuildTasks.dll" />
<Target Name="RefreshVersionBuildTask" BeforeTargets="Pack" Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<RefreshVersion CurrentVersionString="$(PackageVersion)">
<Output TaskParameter="NewVersionString" PropertyName="NewVersionString" />
</RefreshVersion>
<Message Text="Updating package version number to $(NewVersionString)..." Importance="high" />
<XmlPoke XmlInputPath="$(MSBuildProjectDirectory)\mustache.website.sdk.dotNET.csproj" Query="/Project/PropertyGroup/PackageVersion" Value="$(NewVersionString)" />
</Target>
...
<PropertyGroup>
..
<PackageVersion>1.1.4</PackageVersion>
..
当选择Visual Studio Pack项目选项(只需更改为BeforeTargets="Build"
以在构建之前执行任务)时,RefreshVersion代码将被触发以计算新的版本号,并且XmlPoke
任务将相应地更新您的.csproj属性(是的,它会修改文件)。
在使用NuGet库时,我还通过向上一个示例添加下一个构建任务来将软件包发送到NuGet存储库。
<Message Text="Uploading package to NuGet..." Importance="high" />
<Exec WorkingDirectory="$(MSBuildProjectDirectory)\bin\release" Command="c:\nuget\nuget push *.nupkg -Source https://www.nuget.org/api/v2/package" IgnoreExitCode="true" />
c:\nuget\nuget
是我安装 NuGet 客户端的路径(记得通过调用 nuget SetApiKey <my-api-key>
命令来保存你的 NuGet API 密钥,或者在 NuGet 推送时包含密钥)。
希望这能帮到有需要的人 ^_^。