Search code examples
visual-studiomsbuildnugetmsbuild-task.net-standard-2.1

Read a nuget package library version in the target assembly when installed


How to find the installing package library version in the target assembly?

Assume that:

We have NugetLib and ConsumerApp (which will install NugetLib).

I am using .targets file in NugetLib named the same, and it will run on the target when installed.

Inside NugetLib.targets file:

  <Target Name="Main" AfterTargets="Build">
    <Message Text="$(NugetLibVersion)" Importance="high" />
  </Target>

Currently I don't have the correct value of NugetLibVersion, and it needs to be set somehow.

Using $(PackageVersion)" will not help, cause it doesn't read and provide NugetLib version, it will provide ConsumerApp version (the target assembly, which will always be 1.0.0.0).

If you know a way achieving this including setting some special properties, or even by using text files, or any other own or tricky methods are all welcome and appreciated.


Solution

  • If your project is new sdk style format, you can just add this custom target to get the nuget version:

      <Target Name="PrintPackageReferences" AfterTargets="Build">
        
        <Message Text="Dependencies:%0A  @(PackageReference->'%(Identity), Version: %(Version)', '%0A    ')" Importance="High" />
    
        <CreateProperty Condition="'%(PackageReference.Identity)'=='NugetLib'" Value="%(PackageReference.Version)">
         <Output TaskParameter="Value" PropertyName="NugetLibVersion" />
        </CreateProperty>
    
        <Message Importance="high" Text="$(NugetLibVersion)"></Message>
        
        </Target>