1

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

Any idea?

Thank you!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Tester User
  • 175
  • 2
  • 9
  • possible duplicate issue [How do I enable NuGet Package Restore in Visual Studio](https://stackoverflow.com/questions/27895504/how-do-i-enable-nuget-package-restore-in-visual-studio) – Power Mouse Aug 09 '19 at 14:38
  • But I'm looking to do it programmatically with c# code! – Tester User Aug 09 '19 at 14:45
  • Does this answer your question? [Programmatically with C# code restore PackageReferences](https://stackoverflow.com/questions/57569964/programmatically-with-c-sharp-code-restore-packagereferences) – GazTheDestroyer Apr 27 '20 at 11:48

2 Answers2

1

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)

Alexandru Clonțea
  • 1,746
  • 13
  • 23
0

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();
        }
Chirag
  • 1,683
  • 2
  • 17
  • 26