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.

5
  • 1
    Why not use a shell and actually run dotnet cli? Commented Aug 20, 2019 at 8:55
  • Hm, if I understand it correctly you mean something like Run Command Prompt Commands? With System.Diagnostics.Process.Start("CMD.exe", "dotnet restore '.\myproject.csproj' --packages '.\OutputFolder'"); you can run your dotnet command programmatically. Commented Aug 20, 2019 at 9: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? Commented Aug 20, 2019 at 9: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? Commented Aug 20, 2019 at 9: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. Commented Aug 20, 2019 at 10:05

1 Answer 1

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();
        }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.