Just a learner
Just a learner

Reputation: 28572

How can I add a Nuget package to a project in my Visual Studio extension?

I'm building a Visual Studio extension and I want to add a Specific Nuget package when the user clicks a button. I looked around the Visual Studio SDK and there seems no documentation on how to do this. Any ideas?

Upvotes: 0

Views: 169

Answers (1)

Matt Ward
Matt Ward

Reputation: 47937

There is an IVsPackageInstaller you can use to install a NuGet package from within Visual Studio.

Install the NuGet.VisualStudio NuGet package and then use MEF to get access to it.

//Using the Import attribute
[Import(typeof(IVsPackageInstaller2))]
public IVsPackageInstaller2 packageInstaller;
packageInstaller.InstallLatestPackage(null, currentProject,
    "Newtonsoft.Json", false, false);

//Using the IComponentModel service
var componentModel = (IComponentModel)GetService(typeof(SComponentModel));
IVsPackageInstallerServices installerServices =
    componentModel.GetService<IVsPackageInstallerServices>();

var installedPackages = installerServices.GetInstalledPackages();

The above was extracted from the documentation on the NuGet site:

https://learn.microsoft.com/en-us/nuget/visual-studio-extensibility/nuget-api-in-visual-studio

Upvotes: 1

Related Questions