Add/Remove Packages Using dotnet CLI Tool

With the release of .NET Core RC3, the tooling has undergone signinficant improvements in fixing bugs and stablilty. With this release the team has added the ability to add/remove NuGet packages to your project using the dotnet command. The .NET Core CLI tools were introduced to make it easier for developers who uses command line to create and manage projects and with this addition they will become more productive.

Let's create a sample console application project and see how we can add/remove NuGet packages to and from the project. To create the project execute the following command.

dotnet new console

When the command is executed, two files will be created. One is the source file and other one is the project file

Program.cs

namespace AddPackagageSample
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}

csproj file

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.0</TargetFramework>
  </PropertyGroup>

</Project>

 To see this project in action, let's restore the packages and build it as shown below

Let's modify the Program.cs file to do some Json Serialiazation as shown below

using System;
using Newtonsoft.Json;
namespace AddPackagageSample
{
    class Program
    {
        static void Main(string[] args)
        {
            Product p = new Product() { Name = "shoe", Price="10" };
            
            var str = JsonConvert.SerializeObject(p);
            Console.WriteLine($"Hello World! {str}");
            Console.ReadKey();
        }
    }
    class Product
    {
        public string Name { get; set; }
        public string Price { get; set; }
    }
}

If try to build the project now, you will get an error like the one given below

The type or namespace name 'Newtonsoft' could not be found (are you missing a using directive or an assembly reference?)

Adding a Package

To correct this, we need to add the NuGet package for Newtonsoft Json using the dotnet add command

Syntax

dotnet add package <package name>

Usage 

dotnet add package Newtonsoft.Json

If you open the csproj file, you will see that the reference has been added to the file

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Newtonsoft.json">
      <Version>9.0.1</Version>
    </PackageReference>
  </ItemGroup>
</Project>

If you restore the package and execute the project, it will be compiled without any errors and output the serialized string as shown below

Removing a Package

To remove a package from the project, we can make use of the dotnet remove command

Syntax 

dotnet remove package <package name>

Usage 

dotnet remove package Newtonsoft.Json

   


Categories: C#, DotNet CLI


No Comments

Post Reply