I want to programmatically install a NuGet package to a project, and update the .csproj file, and the packages.config 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));
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)