How to autogenerate a nuget package and specify the version?

Kat Lim Ruiz
2 min readMar 24, 2020

When you have a library that you want to publish as a nuget package, you normally have to call nuget pack and nuget push .

And if you use a pipeline, like in Azure Pipelines, you would call this task to pack the library.

- task: NuGetCommand@2
displayName: 'nuget pack'
inputs:
command: pack
packagesToPack: MyLib.nuspec
packDestination: /out
versioningScheme: # off, byPrereleaseNumber, byEnvVar, byBuildNumber

And this task to publish it.

- task: NuGetCommand@2
displayName: 'nuget push'
inputs:
command: push
packagesToPush: /out/*.nupkg
nuGetFeedType: # internal, external
publishVstsFeed: # feed url

In .NET Core projects, things can be done a little differently.

You can set the <GeneratePackageOnBuild>true</GeneratePackageOnBuild> property in the csproj file so every build will generate the nupkg file. Or you can enable it in Project Properties/Package/Generate NuGet package on build.

This would generate a nuget package file bin/Release/MyLib.1.0.3.0.nupkg with the corresponding version.

In .NET Core projects, the version is located inside the csproj file (like nodejs does it because the version is in package.json file). So, in order to set the version, you can either:

  1. Set manually in Visual Studio just before committing your changes.
  2. Set automatically in your pipeline.
  3. Or perhaps a combination of both (manually set the major.minor, and let the pipeline set the patch).

In my case, I want to set the version number automatically because these are internal nuget packages (we use Azure Artifacts for this).

When you manually do the nuget pack and publish, the version number can be assigned to the package after the build, but in our case where we want to use GeneratePackageOnBuild=true, then the version has to be set before building the project.

Since the version field is a property inside the csproj file, then you can actually set it from the command line like any other property.

# set the build number
name: $(Year:yyyy).$(Month).$(DayOfMonth).$(BuildID)
...- task: VSBuild@1
inputs:
solution: MyLib.sln
platform: Any CPU
configuration: Release
msbuildArgs: /p:Version=$(Build.BuildNumber)

In my case I use the build number (coming from the name instruction that I normally put at the beginning of the file), but you can set any other value needed.

Happy coding!

--

--

Kat Lim Ruiz

Software Engineer, father, technology enthusiast, agilist, INTJ, Developer, Mini-Devops.