Click here to Skip to main content
15,916,280 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to programmatically install a NuGet package to a project, and update the .csproj file, and the packages.config file.
Right now i can add DLL from Nuget to package.config,but i couldn't update .cs proj file.

string packageID = "Newtonsoft.json";
var sourceUri = new Uri("https://packages.nuget.org/api/v2");

// Return an IPackage
var package = GetNugetPackage(packageID, sourceUri);

IPackageRepository sourceRepository = PackageRepositoryFactory.Default.CreateRepository(sourceUri.ToString());

string packagesPath = "../../TestFiles/packages";
PackageManager packageManager = new PackageManager(sourceRepository, packagesPath);

packageManager.InstallPackage(packageID, SemanticVersion.Parse(package.Version.ToFullString()));

// ---- Update the ‘packages.config’ file ----
var packageReferenceFile = new PackageReferenceFile("../../TestFiles/packages.config");

// Get the target framework of the current project to add --> targetframework="net452" attribute in the package.config file
var currentTargetFw = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(TargetFrameworkAttribute), false);
var targetFrameworkAttribute = ((TargetFrameworkAttribute[])currentTargetFw).FirstOrDefault();

// Update the packages.config file    
packageReferenceFile.AddEntry(package.GetFullName(), SemanticVersion.Parse(package.Version.ToFullString()), false, new FrameworkName(targetFrameworkAttribute.FrameworkName));


What I have tried:

StackOverflow: How to programmatically install a NuGet package?[^]
Posted
Updated 19-Feb-17 17:58pm
v5
Comments
Graeme_Grant 19-Feb-17 23:52pm    
I am not following. What steps are you currently doing?

1 solution

Maybe one of these YouTube Videos[^] will answer your question for you.

Edit: With the link provided by you, Thomas gives a great solution in his Answer[^]
 
Share this answer
 
v2
Comments
shamjid 20-Feb-17 0:23am    
From Thomas solution,i can't access "MSBuildProjectSystem" even though i refered Nuget.core reference.That is what my problem

"var project = new MSBuildProjectSystem(csprojFilePath); "
Graeme_Grant 20-Feb-17 0:25am    
I'm not going to debug your code for you. Post your question to Thomas [edit: on stackoverflow] as it is his code that you are using. Maybe he has some pointers for you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900