1

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.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Tester User
  • 175
  • 2
  • 9
  • 1
    Why not use a shell and actually run dotnet cli? – EliSherer Aug 20 '19 at 08:55
  • Hm, if I understand it correctly you mean something like [Run Command Prompt Commands](https://stackoverflow.com/questions/1469764/run-command-prompt-commands)? With `System.Diagnostics.Process.Start("CMD.exe", "dotnet restore '.\myproject.csproj' --packages '.\OutputFolder'");` you can run your dotnet command programmatically. – Mar Tin Aug 20 '19 at 09:15
  • @EliSherer It can be a solution, but when I’ll deploy it to a specific environment with windows/linux machine host it will work or not! What do you think? – Tester User Aug 20 '19 at 09:23
  • @MarTin when I’ll deploy it to a specific environment with windows/linux machine host it will provoke **risks** or not! What do you think? – Tester User Aug 20 '19 at 09:41
  • Yes it will. But you can check and handle the enviroment before the execution. `Environment.OSVersion.Platform` to check platform. Or `var values = Environment.GetEnvironmentVariable("PATH");` to check `cmd.exe`. It is always a risk to execute 3rd party. It is the same for **dotnet**. You have to proof **dotnet** exist as enviroment PATH variable before. – Mar Tin Aug 20 '19 at 10:05

1 Answers1

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