使用MSBuild脚本,我们如何从AssemblyInfo.cs中获取AssemblyVersion和FileVersion?
如何在MSBuild脚本中从AssemblyInfo.cs获取AssmeblyVersion和FileVersion?
要通过MSBuild获取AssmeblyVersion
,您可以使用GetAssemblyIdentity任务。
要实现此操作,请卸载项目。然后在项目的末尾标记</Project>
之前,插入以下脚本:
<Target Name="GetAssmeblyVersion" AfterTargets="Build">
<GetAssemblyIdentity
AssemblyFiles="$(TargetPath)">
<Output
TaskParameter="Assemblies"
ItemName="MyAssemblyIdentities"/>
</GetAssemblyIdentity>
<Message Text="Assmebly Version: %(MyAssemblyIdentities.Version)"/>
</Target>
要获取FileVersion
,您可以添加自定义MSBuild内联任务来实现,编辑您的项目文件.csproj
,添加以下代码:
<UsingTask
TaskName="GetFileVersion"
TaskFactory="CodeTaskFactory"
AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
<ParameterGroup>
<AssemblyPath ParameterType="System.String" Required="true" />
<Version ParameterType="System.String" Output="true" />
</ParameterGroup>
<Task>
<Using Namespace="System.Diagnostics" />
<Code Type="Fragment" Language="cs">
<![CDATA[
Log.LogMessage("Getting version details of assembly at: " + this.AssemblyPath, MessageImportance.High);
this.Version = FileVersionInfo.GetVersionInfo(this.AssemblyPath).FileVersion;
]]>
</Code>
</Task>
</UsingTask>
<Target Name="GetFileVersion" AfterTargets="Build">
<GetFileVersion AssemblyPath="$(TargetPath)">
<Output TaskParameter="Version" PropertyName="MyAssemblyFileVersion" />
</GetFileVersion>
<Message Text="File version is $(MyAssemblyFileVersion)" />
</Target>
在完成这两个目标后,您将可以从AssemblyInfo.cs
获取AssmeblyVersion
和FileVersion
:
注意:如果您想获得特定dll的版本,可以将AssemblyFiles="$(TargetPath)"
更改为:
<PropertyGroup>
<MyAssemblies>somedll\the.dll</MyAssemblies>
</PropertyGroup>
AssemblyFiles="@(MyAssemblies)"
希望这能帮到你。
RoslynCodeTaskFactory
。https://dev59.com/sXsPtIcB2Jgan1zn_1xIhttps://learn.microsoft.com/en-us/visualstudio/msbuild/msbuild-roslyncodetaskfactory?view=vs-2022 - Lydon Ch