After struggling with NuGet.VisualStudio and NuGet.Core packages and spending so much time, I've found out that the best approach is to use NuGet CLI and .NET Process object. After downloading nuget.exe this is how to update packages:
var updateOutput = new List<string>();
var updateError = new List<string>();
var updateProcess = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "the path to nuget.exe file",
Arguments = "update " + "project path including .csproj file",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
}
};
updateProcess.Start();
while (!updateProcess.StandardOutput.EndOfStream)
{
updateOutput.Add(updateProcess.StandardOutput.ReadLine());
}
while (!updateProcess.StandardError.EndOfStream)
{
updateError.Add(updateProcess.StandardError.ReadLine());
}
After that what you do with updateOutput and updateError is your decision based on your needs.
Note: In my case I had project.json for package configuration and nuget.exe needed packages.config file. So, I created a temporary packages.config file and after updating packages I deleted it. Like this:
var ProjectPath = "the path to project folder";
var input = new StringBuilder();
input.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
input.AppendLine("<packages>");
using (var r = new StreamReader(ProjectPath + @"\project.json"))
{
var json = r.ReadToEnd();
dynamic array = JsonConvert.DeserializeObject(json);
foreach (var item in array.dependencies)
{
var xmlNode = item.ToString().Split(':');
input.AppendLine("<package id=" + xmlNode[0] + " version=" + xmlNode[1] + " />");
}
}
input.AppendLine("</packages>");
var doc = new XmlDocument();
doc.LoadXml(input.ToString());
doc.Save(ProjectPath + @"\packages.config");
// After updating packages
File.Delete(ProjectPath + @"\packages.config");