Reputation: 2749
Given a string file path to a solution file e.g. C:\Foo.sln, how do you programmatically restore NuGet packages for that solution? I've tried to follow this guide, but have found that it's woefully incomplete.
After installing NuGet package NuGet.VisualStudio as the article recommends, I'm floundering about trying to restore packages.
Here's the code I have so far:
// requires reference to System.ComponentModel.Composition
[Import(typeof(IVsPackageRestorer))]
private static IVsPackageRestorer packageInstaller;
And then trying to use it (seems to require EnvDTE reference) (and how does one use this magic "GetService" method - where does that come from?):
private static void RestorePackages(string solutionPath)
{
// Using the IComponentModel service
// https://learn.microsoft.com/en-us/nuget/visual-studio-extensibility/nuget-api-in-visual-studio#ivspackagerestorer-interface
// How do I get the project? Can I do this at the solution level or do I have to get all projects under the solution?
EnvDTE.Project project = null;
packageInstaller.RestorePackages(project);
////What is this code??? What is GetService???
////var componentModel = (IComponentModel)GetService(typeof(SComponentModel));
////IVsPackageRestorer packageRestorer = componentModel.GetService<IVsPackageRestorer>();
////packageRestorer.RestorePackages(project);
}
Edit/Solution: Using Matt Ward's recommendation, the code to "shell out" to nuget.exe looks like the following method in my case to restore packages based on the full path to a solution.
private static void RestorePackages(string solutionPath)
{
using (Process process = new Process())
{
process.StartInfo = new ProcessStartInfo
{
FileName = "nuget.exe",
Arguments = $"restore {solutionPath}",
UseShellExecute = false,
CreateNoWindow = true
};
process.Start();
process.WaitForExit();
}
}
Upvotes: 3
Views: 2082
Reputation: 47917
Not sure where your code is running from. It may be simpler to just shell out to NuGet.exe and restore the solution instead of trying to use the Visual Studio API. The API you link to is only available if you are running from within Visual Studio as an extension or in the Package Manager Console window, for example.
If the code you are writing is not running within Visual Studio, say it is a console app, then running nuget.exe is going to be easier. Otherwise you could look at the various NuGet packages that are available to be used and provide an API to do various NuGet operations. However running nuget.exe restore is much simpler to do.
Upvotes: 2