以编程方式更新NuGet包

时间:2017-08-22 08:58:29

标签: c# uwp nuget

我见过许多关于安装NuGet软件包的问题和示例,但没有关于更新软件包的问题和示例。

更新NuGet套餐的最佳方法是什么?我正在尝试从ASP.NET MVC应用程序执行此操作以更新UWP项目中的包,其中projec.json用于包引用。

我是否还需要更新.csprojproject.json个文件?

1 个答案:

答案 0 :(得分:2)

在与NuGet.VisualStudioNuGet.Core软件包挣扎并花费了大量时间之后,我发现最好的方法是使用NuGet CLI和.NET Process对象。下载nuget.exe后,这是更新包的方法:

            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());
            }

之后,您根据自己的需要决定使用updateOutputupdateError做什么。

注意:在我的情况下,我有project.json用于包配置,nuget.exe需要packages.config文件。所以,我创建了一个临时的packages.config文件,在更新包之后我删除了它。像这样:

            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");
相关问题