Tester User
Tester User

Reputation: 225

Restore nuget packages Programmatically (.net core & .net framework)

I want to restore nuget packages programmatically for .net core and .net Framework based on Packages.config & package references.

Any idea?

Thank you!

Upvotes: 1

Views: 1131

Answers (2)

Chirag
Chirag

Reputation: 1853

If using shell is ok, You may try following steps to restore nuget packages using c#.

  1. Download latest version of Nuget.exe from NuGet Gallery Downloads
  2. Add Nuget.exe to your C# project and mark as "Copy if newer" to Copy to Output Directory
  3. Run below RestorePackages() method with solution path as parameter

        public static void RestorePackages(string solutionPath)
        {
            var dir = AppDomain.CurrentDomain.BaseDirectory;
            ProcessStartInfo objPI = new ProcessStartInfo($"{dir}\\nuget.exe", $"restore \"{solutionPath}\" -Verbosity quiet");
            objPI.RedirectStandardError = true;
            objPI.RedirectStandardOutput = true;
            objPI.UseShellExecute = false;

            Process objProcess = Process.Start(objPI);
            string error = objProcess.StandardError.ReadToEnd();
            string output = objProcess.StandardOutput.ReadToEnd();

            objProcess.WaitForExit();
        }

Upvotes: 0

Alexandru Clonțea
Alexandru Clonțea

Reputation: 1866

The nuget.exe tool deals with both cases. So instead of "msbuild /t:Restore" or "dotnet restore", just run "nuget restore". If you want to do it programatically, you can use the nuget package Nuget.CommandLine (install via Nuget or Chocolatey, depending on your needs)

Upvotes: 1

Related Questions