Create Nuget Package Visual Studio

  1. Create Nuget Package Visual Studio 2017 Tutorial
  2. Download Nuget Package Visual Studio

Create a class library project. You can use an existing.NET Standard Class Library project for the code you want to package or create a simple one as follows: Step 1. In Visual Studio, choose File New Project, expand the Visual C#.NET Standard node, select the 'Class Library (.NET Standard)' template, name the project ownNuGet,. Install the visual studio extension that adds the NuGet package template to your Visual Studio. Create Project Using the NuGetPackage.Project.NuGet template. In the project, you will find the following files. Internalpackages.config; NuGetPack.config; packages.config; For Starters, the below extract from the readme.txt file is quite explanatory 1.

-->

No matter what your package does or what code it contains, you use one of the CLI tools, either nuget.exe or dotnet.exe, to package that functionality into a component that can be shared with and used by any number of other developers. To install NuGet CLI tools, see Install NuGet client tools. Note that Visual Studio does not automatically include a CLI tool.

  • For non-SDK-style projects, typically .NET Framework projects, follow the steps described in this article to create a package. For step-by-step instructions using Visual Studio and the nuget.exe CLI, see Create and publish a .NET Framework package.

  • For .NET Core and .NET Standard projects that use the SDK-style format, and any other SDK-style projects, see Create a NuGet package using the dotnet CLI.

  • For projects migrated from packages.config to PackageReference, use msbuild -t:pack.

Technically speaking, a NuGet package is just a ZIP file that's been renamed with the .nupkg extension and whose contents match certain conventions. This topic describes the detailed process of creating a package that meets those conventions.

Packaging begins with the compiled code (assemblies), symbols, and/or other files that you want to deliver as a package (see Overview and workflow). This process is independent from compiling or otherwise generating the files that go into the package, although you can draw from information in a project file to keep the compiled assemblies and packages in sync.

Important

This topic applies to non-SDK-style projects, typically projects other than .NET Core and .NET Standard projects using Visual Studio 2017 and higher versions and NuGet 4.0+.

Decide which assemblies to package

Most general-purpose packages contain one or more assemblies that other developers can use in their own projects.

  • In general, it's best to have one assembly per NuGet package, provided that each assembly is independently useful. For example, if you have a Utilities.dll that depends on Parser.dll, and Parser.dll is useful on its own, then create one package for each. Doing so allows developers to use Parser.dll independently of Utilities.dll.

  • If your library is composed of multiple assemblies that aren't independently useful, then it's fine to combine them into one package. Using the previous example, if Parser.dll contains code that's used only by Utilities.dll, then it's fine to keep Parser.dll in the same package.

  • Similarly, if Utilities.dll depends on Utilities.resources.dll, where again the latter is not useful on its own, then put both in the same package.

Resources are, in fact, a special case. When a package is installed into a project, NuGet automatically adds assembly references to the package's DLLs, excluding those that are named .resources.dll because they are assumed to be localized satellite assemblies (see Creating localized packages). For this reason, avoid using .resources.dll for files that otherwise contain essential package code.

If your library contains COM interop assemblies, follow additional the guidelines in Create packages with COM interop assemblies.

The role and structure of the .nuspec file

Once you know what files you want to package, the next step is creating a package manifest in a .nuspec XML file.

The manifest:

  1. Describes the package's contents and is itself included in the package.
  2. Drives both the creation of the package and instructs NuGet on how to install the package into a project. For example, the manifest identifies other package dependencies such that NuGet can also install those dependencies when the main package is installed.
  3. Contains both required and optional properties as described below. For exact details, including other properties not mentioned here, see the .nuspec reference.

Required properties:

  • The package identifier, which must be unique across the gallery that hosts the package.
  • A specific version number in the form Major.Minor.Patch[-Suffix] where -Suffix identifies pre-release versions
  • The package title as it should appear on the host (like nuget.org)
  • Author and owner information.
  • A long description of the package.

Common optional properties:

  • Release notes
  • Copyright information
  • A short description for the Package Manager UI in Visual Studio
  • A locale ID
  • Project URL
  • License as an expression or file (licenseUrl is deprecated, use license nuspec metadata element instead)
  • An icon file (iconUrl is deprecated use icon nuspec metadata element instead)
  • Lists of dependencies and references
  • Tags that assist in gallery searches

The following is a typical (but fictitious) .nuspec file, with comments describing the properties:

For details on declaring dependencies and specifying version numbers, see packages.config and Package versioning. It is also possible to surface assets from dependencies directly in the package by using the include and exclude attributes on the dependency element. See .nuspec Reference - Dependencies.

Because the manifest is included in the package created from it, you can find any number of additional examples by examining existing packages. A good source is the global-packages folder on your computer, the location of which is returned by the following command:

Go into any packageversion folder, copy the .nupkg file to a .zip file, then open that .zip file and examine the .nuspec within it.

Note

When creating a .nuspec from a Visual Studio project, the manifest contains tokens that are replaced with information from the project when the package is built. See Creating the .nuspec from a Visual Studio project.

Create the .nuspec file

Creating a complete manifest typically begins with a basic .nuspec file generated through one of the following methods:

You then edit the file by hand so that it describes the exact content you want in the final package.

Important

Create Nuget Package Visual Studio 2017 Tutorial

Generated .nuspec files contain placeholders that must be modified before creating the package with the nuget pack command. That command fails if the .nuspec contains any placeholders.

From a convention-based working directory

Because a NuGet package is just a ZIP file that's been renamed with the .nupkg extension, it's often easiest to create the folder structure you want on your local file system, then create the .nuspec file directly from that structure. The nuget pack command then automatically adds all files in that folder structure (excluding any folders that begin with ., allowing you to keep private files in the same structure).

The advantage to this approach is that you don't need to specify in the manifest which files you want to include in the package (as explained later in this topic). You can simply have your build process produce the exact folder structure that goes into the package, and you can easily include other files that might not be part of a project otherwise:

  • Content and source code that should be injected into the target project.
  • PowerShell scripts
  • Transformations to existing configuration and source code files in a project.

The folder conventions are as follows:

FolderDescriptionAction upon package install
(root)Location for readme.txtVisual Studio displays a readme.txt file in the package root when the package is installed.
lib/{tfm}Assembly (.dll), documentation (.xml), and symbol (.pdb) files for the given Target Framework Moniker (TFM)Assemblies are added as references for compile as well as runtime; .xml and .pdb copied into project folders. See Supporting multiple target frameworks for creating framework target-specific sub-folders.
ref/{tfm}Assembly (.dll), and symbol (.pdb) files for the given Target Framework Moniker (TFM)Assemblies are added as references only for compile time; So nothing will be copied into project bin folder.
runtimesArchitecture-specific assembly (.dll), symbol (.pdb), and native resource (.pri) filesAssemblies are added as references only for runtime; other files are copied into project folders. There should always be a corresponding (TFM) AnyCPU specific assembly under /ref/{tfm} folder to provide corresponding compile time assembly. See Supporting multiple target frameworks.
contentArbitrary filesContents are copied to the project root. Think of the content folder as the root of the target application that ultimately consumes the package. To have the package add an image in the application's /images folder, place it in the package's content/images folder.
build(3.x+) MSBuild .targets and .props filesAutomatically inserted into the project.
buildMultiTargeting(4.0+) MSBuild .targets and .props files for cross-framework targetingAutomatically inserted into the project.
buildTransitive(5.0+) MSBuild .targets and .props files that flow transitively to any consuming project. See the feature page.Automatically inserted into the project.
toolsPowershell scripts and programs accessible from the Package Manager ConsoleThe tools folder is added to the PATH environment variable for the Package Manager Console only (Specifically, not to the PATH as set for MSBuild when building the project).

Because your folder structure can contain any number of assemblies for any number of target frameworks, this method is necessary when creating packages that support multiple frameworks.

In any case, once you have the desired folder structure in place, run the following command in that folder to create the .nuspec file:

Again, the generated .nuspec contains no explicit references to files in the folder structure. NuGet automatically includes all files when the package is created. You still need to edit placeholder values in other parts of the manifest, however.

From an assembly DLL

In the simple case of creating a package from an assembly, you can generate a .nuspec file from the metadata in the assembly using the following command:

Using this form replaces a few placeholders in the manifest with specific values from the assembly. For example, the <id> property is set to the assembly name, and <version> is set to the assembly version. Other properties in the manifest, however, don't have matching values in the assembly and thus still contain placeholders.

From a Visual Studio project

Creating a .nuspec from a .csproj or .vbproj file is convenient because other packages that have been installed into those project are automatically referenced as dependencies. Simply use the following command in the same folder as the project file:

The resulting <project-name>.nuspec file contains tokens that are replaced at packaging time with values from the project, including references to any other packages that have already been installed.

If you have package dependencies to include in the .nuspec, instead use nuget pack, and get the .nuspec file from within the generated .nupkg file. For example, use the following command.

A token is delimited by $ symbols on both sides of the project property. For example, the <id> value in a manifest generated in this way typically appears as follows:

This token is replaced with the AssemblyName value from the project file at packing time. For the exact mapping of project values to .nuspec tokens, see the Replacement Tokens reference.

Tokens relieve you from needing to update crucial values like the version number in the .nuspec as you update the project. (You can always replace the tokens with literal values, if desired).

Note that there are several additional packaging options available when working from a Visual Studio project, as described in Running nuget pack to generate the .nupkg file later on.

Solution-level packages

NuGet 2.x only. Not available in NuGet 3.0+.

NuGet 2.x supported the notion of a solution-level package that installs tools or additional commands for the Package Manager Console (the contents of the tools folder), but does not add references, content, or build customizations to any projects in the solution. Such packages contain no files in its direct lib, content, or build folders, and none of its dependencies have files in their respective lib, content, or build folders.

NuGet tracks installed solution-level packages in a packages.config file in the .nuget folder, rather than the project's packages.config file.

Create

New file with default values

The following command creates a default manifest with placeholders, which ensures you start with the proper file structure:

If you omit <package-name>, the resulting file is Package.nuspec. If you provide a name such as Contoso.Utility.UsefulStuff, the file is Contoso.Utility.UsefulStuff.nuspec.

The resulting .nuspec contains placeholders for values like the projectUrl. Be sure to edit the file before using it to create the final .nupkg file.

Choose a unique package identifier and setting the version number

The package identifier (<id> element) and the version number (<version> element) are the two most important values in the manifest because they uniquely identify the exact code that's contained in the package.

Best practices for the package identifier:

  • Uniqueness: The identifier must be unique across nuget.org or whatever gallery hosts the package. Before deciding on an identifier, search the applicable gallery to check if the name is already in use. To avoid conflicts, a good pattern is to use your company name as the first part of the identifier, such as Contoso..
  • Namespace-like names: Follow a pattern similar to namespaces in .NET, using dot notation instead of hyphens. For example, use Contoso.Utility.UsefulStuff rather than Contoso-Utility-UsefulStuff or Contoso_Utility_UsefulStuff. Consumers also find it helpful when the package identifier matches the namespaces used in the code.
  • Sample Packages: If you produce a package of sample code that demonstrates how to use another package, attach .Sample as a suffix to the identifier, as in Contoso.Utility.UsefulStuff.Sample. (The sample package would of course have a dependency on the other package.) When creating a sample package, use the convention-based working directory method described earlier. In the content folder, arrange the sample code in a folder called Samples<identifier> as in SamplesContoso.Utility.UsefulStuff.Sample.

Best practices for the package version:

  • In general, set the version of the package to match the library, though this is not strictly required. This is a simple matter when you limit a package to a single assembly, as described earlier in Deciding which assemblies to package. Overall, remember that NuGet itself deals with package versions when resolving dependencies, not assembly versions.
  • When using a non-standard version scheme, be sure to consider the NuGet versioning rules as explained in Package versioning.

The following series of brief blog posts are also helpful to understand versioning:

Add a readme and other files

To directly specify files to include in the package, use the <files> node in the .nuspec file, which follows the <metadata> tag:

Tip

When using the convention-based working directory approach, you can place the readme.txt in the package root and other content in the content folder. No <file> elements are necessary in the manifest.

When you include a file named readme.txt in the package root, Visual Studio displays the contents of that file as plain text immediately after installing the package directly. (Readme files are not displayed for packages installed as dependencies). For example, here's how the readme for the HtmlAgilityPack package appears:

Note

If you include an empty <files> node in the .nuspec file, NuGet doesn't include any other content in the package other than what's in the lib folder.

Include MSBuild props and targets in a package

In some cases, you might want to add custom build targets or properties in projects that consume your package, such as running a custom tool or process during build. You do this by placing files in the form <package_id>.targets or <package_id>.props (such as Contoso.Utility.UsefulStuff.targets) within the build folder of the project.

Files in the root build folder are considered suitable for all target frameworks. To provide framework-specific files, first place them within appropriate subfolders, such as the following:

Then in the .nuspec file, be sure to refer to these files in the <files> node:

Including MSBuild props and targets in a package was introduced with NuGet 2.5, therefore it is recommended to add the minClientVersion='2.5' attribute to the metadata element, to indicate the minimum NuGet client version required to consume the package.

When NuGet installs a package with build files, it adds MSBuild <Import> elements in the project file pointing to the .targets and .props files. (.props is added at the top of the project file; .targets is added at the bottom.) A separate conditional MSBuild <Import> element is added for each target framework.

MSBuild .props and .targets files for cross-framework targeting can be placed in the buildMultiTargeting folder. During package installation, NuGet adds the corresponding <Import> elements to the project file with the condition, that the target framework is not set (the MSBuild property $(TargetFramework) must be empty).

With NuGet 3.x, targets are not added to the project but are instead made available through {projectName}.nuget.g.targets and {projectName}.nuget.g.props.

Run nuget pack to generate the .nupkg file

Create nuget package visual studio .net framework

When using an assembly or the convention-based working directory, create a package by running nuget pack with your .nuspec file, replacing <project-name> with your specific filename:

When using a Visual Studio project, run nuget pack with your project file, which automatically loads the project's .nuspec file and replaces any tokens within it using values in the project file:

Note

Using the project file directly is necessary for token replacement because the project is the source of the token values. Token replacement does not happen if you use nuget pack with a .nuspec file.

In all cases, nuget pack excludes folders that start with a period, such as .git or .hg.

NuGet indicates if there are any errors in the .nuspec file that need correcting, such as forgetting to change placeholder values in the manifest.

Once nuget pack succeeds, you have a .nupkg file that you can publish to a suitable gallery as described in Publishing a Package.

Tip

A helpful way to examine a package after creating it is to open it in the Package Explorer tool. This gives you a graphical view of the package contents and its manifest. You can also rename the resulting .nupkg file to a .zip file and explore its contents directly.

Additional options

You can use various command-line switches with nuget pack to exclude files, override the version number in the manifest, and change the output folder, among other features. For a complete list, refer to the pack command reference.

The following options are a few that are common with Visual Studio projects:

  • Referenced projects: If the project references other projects, you can add the referenced projects as part of the package, or as dependencies, by using the -IncludeReferencedProjects option:

    This inclusion process is recursive, so if MyProject.csproj references projects B and C, and those projects reference D, E, and F, then files from B, C, D, E, and F are included in the package.

    If a referenced project includes a .nuspec file of its own, then NuGet adds that referenced project as a dependency instead. You need to package and publish that project separately.

  • Build configuration: By default, NuGet uses the default build configuration set in the project file, typically Debug. To pack files from a different build configuration, such as Release, use the -properties option with the configuration:

  • Symbols: to include symbols that allow consumers to step through your package code in the debugger, use the -Symbols option:

Test package installation

Before publishing a package, you typically want to test the process of installing a package into a project. The tests make sure that the necessarily files all end up in their correct places in the project.

You can test installations manually in Visual Studio or on the command line using the normal package installation steps.

For automated testing, the basic process is as follows:

  1. Copy the .nupkg file to a local folder.
  2. Add the folder to your package sources using the nuget sources add -name <name> -source <path> command (see nuget sources). Note that you need only set this local source once on any given computer.
  3. Install the package from that source using nuget install <packageID> -source <name> where <name> matches the name of your source as given to nuget sources. Specifying the source ensures that the package is installed from that source alone.
  4. Examine your file system to check that files are installed correctly.

Next Steps

Once you've created a package, which is a .nupkg file, you can publish it to the gallery of your choice as described on Publishing a Package.

You might also want to extend the capabilities of your package or otherwise support other scenarios as described in the following topics:

Finally, there are additional package types to be aware of:

-->

A package for Xamarin contains code that uses native APIs on iOS, Android, and Windows, depending on the run-time operating system. Although this is straightforward to do, it's preferable to let developers consume the package from a PCL or .NET Standard libraries through a common API surface area.

In this walkthrough you use Visual Studio 2017 or 2019 to create a cross-platform NuGet package that can be used in mobile projects on iOS, Android, and Windows.

Prerequisites

  1. Visual Studio 2017 or 2019 with Universal Windows Platform (UWP) and Xamarin. Install the Community edition for free from visualstudio.com; you can use the Professional and Enterprise editions as well, of course. To include UWP and Xamarin tools, select a Custom install and check the appropriate options.
  2. NuGet CLI. Download the latest version of nuget.exe from nuget.org/downloads, saving it to a location of your choice. Then add that location to your PATH environment variable if it isn't already.

Note

nuget.exe is the CLI tool itself, not an installer, so be sure to save the downloaded file from your browser instead of running it.

Download Nuget Package Visual Studio

Create the project structure and abstraction code

  1. Download and run the Cross-Platform .NET Standard Plugin Templates extension for Visual Studio. These templates will make it easy to create the necessary project structure for this walkthrough.

  2. In Visual Studio 2017, File > New > Project, search for Plugin, select the Cross-Platform .NET Standard Library Plugin template, change the name to LoggingLibrary, and click OK.

    In Visual Studio 2019, File > New > Project, search for Plugin, select the Cross-Platform .NET Standard Library Plugin template, and click Next.

    Change the name to LoggingLibrary, and click Create.

The resulting solution contains two Shared projects, along with a variety of platform-specific projects:

Studio
  • The ILoggingLibrary project, which is contained in the ILoggingLibrary.shared.cs file, defines the public interface (the API surface area) of the component. This is where you define the interface to your library.
  • The other Shared project contains code in CrossLoggingLibrary.shared.cs that will locate a platform-specific implementation of the abstract interface at run time. You typically don't need to modify this file.
  • The platform-specific projects, such as LoggingLibrary.android.cs, each contain a native implementation of the interface in their respective LoggingLibraryImplementation.cs (VS 2017) or LoggingLibrary.<PLATFORM>.cs (VS 2019) files. This is where you build out your library's code.

By default, the ILoggingLibrary.shared.cs file of the ILoggingLibrary project contains an interface definition, but no methods. For the purposes of this walkthrough, add a Log method as follows:

Write your platform-specific code

To implement a platform-specific implementation of the ILoggingLibrary interface and its methods, do the following:

  1. Open the LoggingLibraryImplementation.cs (VS 2017) or LoggingLibrary.<PLATFORM>.cs (VS 2019) file of each platform project and add the necessary code. For example (using the Android platform project):

  2. Repeat this implementation in the projects for each platform you want to support.

  3. Right-click the solution and select Build Solution to check your work and produce the artifacts that you package next. If you get errors about missing references, right-click the solution, select Restore NuGet Packages to install dependencies, and rebuild.

Note

If you are using Visual Studio 2019, before selecting Restore NuGet Packages and trying to rebuild, you need to change the version of MSBuild.Sdk.Extras to 2.0.54 in LoggingLibrary.csproj. This file can only be accessed by first right-clicking the project (below the solution) and selecting Unload Project, after which you right-click on the unloaded project and select Edit LoggingLibrary.csproj.

Note

To build for iOS you need a networked Mac connected to Visual Studio as described on Introduction to Xamarin.iOS for Visual Studio. If you don't have a Mac available, clear the iOS project in the configuration manager (step 3 above).

Create and update the .nuspec file

  1. Open a command prompt, navigate to the LoggingLibrary folder that's one level below where the .sln file is, and run the NuGet spec command to create the initial Package.nuspec file:

  2. Rename this file to LoggingLibrary.nuspec and open it in an editor.

  3. Update the file to match the following, replacing YOUR_NAME with an appropriate value. The <id> value, specifically, must be unique across nuget.org (see the naming conventions described in Creating a package). Also note that you must also update the author and description tags or you get an error during the packing step.

Tip

You can suffix your package version with -alpha, -beta or -rc to mark your package as pre-release, check Pre-release versions for more information about pre-release versions.

Add reference assemblies

To include platform-specific reference assemblies, add the following to the <files> element of LoggingLibrary.nuspec as appropriate for your supported platforms:

Note

To shorten the names of the DLL and XML files, right-click on any given project, select the Library tab, and change the assembly names.

Add dependencies

If you have specific dependencies for native implementations, use the <dependencies> element with <group> elements to specify them, for example:

For example, the following would set iTextSharp as a dependency for the UAP target:

Final .nuspec

Your final .nuspec file should now look like the following, where again YOUR_NAME should be replaced with an appropriate value:

Package the component

With the completed .nuspec referencing all the files you need to include in the package, you're ready to run the pack command:

This will generate LoggingLibrary.YOUR_NAME.1.0.0.nupkg. Opening this file in a tool like the NuGet Package Explorer and expanding all the nodes, you see the following contents:

Tip

A .nupkg file is just a ZIP file with a different extension. You can also examine package contents, then, by changing .nupkg to .zip, but remember to restore the extension before uploading a package to nuget.org.

To make your package available to other developers, follow the instructions on Publish a package.

Install nupkg file

Related topics