8

Using MSBuild script how can we get AssmeblyVersion and FileVersion from AssemblyInfo.cs?

Leo Liu
  • 71,098
  • 10
  • 114
  • 135
Sujeet Singh
  • 165
  • 3
  • 13

1 Answers1

12

Using MSBuild script how can we get AssmeblyVersion and FileVersion from AssemblyInfo.cs?

To get the AssmeblyVersion via MSBuild, you can use GetAssemblyIdentity Task.

To accomplish this, unload your project. Then at the very end of the project, just before the end-tag </Project>, place below scripts:

  <Target Name="GetAssmeblyVersion" AfterTargets="Build">
    <GetAssemblyIdentity
        AssemblyFiles="$(TargetPath)">
      <Output
          TaskParameter="Assemblies"
          ItemName="MyAssemblyIdentities"/>
    </GetAssemblyIdentity>

    <Message Text="Assmebly Version: %(MyAssemblyIdentities.Version)"/>
  </Target>

To get the FileVersion, you could add a custom MSBuild Inline Tasks to get this, edit your project file .csproj, add following code:

  <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>

After with those two targets, you will get the AssmeblyVersion and FileVersion from AssemblyInfo.cs:

enter image description here

Note:If you want to get the version of a specific dll, you can change the AssemblyFiles="$(TargetPath)" to the:

<PropertyGroup>
    <MyAssemblies>somedll\the.dll</MyAssemblies>
</PropertyGroup>

AssemblyFiles="@(MyAssemblies)"

Hope this helps.

Leo Liu
  • 71,098
  • 10
  • 114
  • 135
  • for dotnet core and above, use `RoslynCodeTaskFactory` https://stackoverflow.com/questions/74126512/error-msb4801-the-task-factory-codetaskfactory-is-not-supported-on-the-net-c https://learn.microsoft.com/en-us/visualstudio/msbuild/msbuild-roslyncodetaskfactory?view=vs-2022 – Lydon Ch Dec 20 '22 at 04:53