Programmatically with C# code restore PackageReferences

582 Views Asked by At

I'm trying programmatically with C# base code to restore packageReference for .NET framework & .NET core projects.

I thought about using dotnet.exe / msbuild.exe but I don't know how!

I want to simulate what we can do with dotnet CLI:

dotnet restore '.\myproject.csproj' --packages '.\OutputFolder' 

but I want to do it programmatically.

Thanks for the answers.

1

There are 1 best solutions below

0
On

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();
        }