Install and use a package using the dotnet CLI

NuGet packages contain reusable code that other developers make available to you for use in your projects. See What is NuGet? for background. Packages are installed into a .NET Core project using the dotnet add package command as described in this article for the popular Newtonsoft.Json package.

Once installed, refer to the package in code with using <namespace> where <namespace> is specific to the package you're using. Once the reference is made, you can call the package through its API.

Tip

Start with nuget.org: Browsing nuget.org is how .NET developers typically find components they can reuse in their own applications. You can search nuget.org directly or find and install packages within Visual Studio as shown in this article.

Pre-requisites

  • The .NET Core SDK, which provides the dotnet command-line tool.

Create a project

NuGet packages can be installed into a .NET project of some kind. For this walkthrough, create a simple .NET Core console project as follows:

  1. Create a folder for the project.

  2. Create the project using the following command:

    dotnet new console
    
  3. Use dotnet run to test that the app has been created properly.

Add the Newtonsoft.Json NuGet package

  1. Use the following command to install the Newtonsoft.json package:

    dotnet add package Newtonsoft.Json
    
  2. After the command completes, open the .csproj file to see the added reference:

    <ItemGroup>
    <PackageReference Include="Newtonsoft.Json" Version="10.0.3" />
    </ItemGroup>
    

Use the Newtonsoft.Json API in the app

  1. Open the Program.cs file and add the following line at the top of the file:

    using Newtonsoft.Json;
    
  2. Add the following code before the class Program line:

    public class Account
    {
        public string Name { get; set; }
        public string Email { get; set; }
        public DateTime DOB { get; set; }
    }
    
  3. Replace the Main function with the following:

    static void Main(string[] args)
    {
        Account account = new Account
        {
            Name = "John Doe",
            Email = "john@nuget.org",
            DOB = new DateTime(1980, 2, 20, 0, 0, 0, DateTimeKind.Utc),
        };
    
        string json = JsonConvert.SerializeObject(account, Formatting.Indented);
        Console.WriteLine(json);
    }
    
  4. Build and run the app by using the dotnet run command. The output should be the JSON representation of the Account object in the code:

    {
      "Name": "John Doe",
      "Email": "john@nuget.org",
      "DOB": "1980-02-20T00:00:00Z"
    }