【问题标题】:Get nuget package version included in csproj in .Net Core 3.1获取 .Net Core 3.1 中 csproj 中包含的 nuget 包版本
【发布时间】:2020-08-07 16:46:45
【问题描述】:

简而言之,我希望能够以编程方式修改 .csproj 文件。

我正在开发一个应用程序,该应用程序将 nuget 包替换为其实际项目参考。这是应用程序用于调试目的。我们在解决方案文件中添加了大量的软件包。为此,我读取了一个 csproj 文件并应用一个正则表达式来查找指定的 nuget 包引用并添加一个项目引用。这部分工作正常,但它不再挑选包裹了。

以上可以使用dotnet 命令完成,但使用它我无法替换旧版本。

是否有任何可用的 Microsoft nuget 包可以读取 csproj 文件中的包引用?

here 提出了类似的问题,但 Build.Engine 在最新版本中不可用。

【问题讨论】:

  • 这里有一些不清楚的地方,为什么要这么做,你用的是什么包格式,你的代码是什么样子的
  • 我正在使用正则表达式来查找包及其版本PackageReference Include=\" packageName ".*Version=\""(\S*)""
  • 使用上面的正则表达式我搜索包引用并将其替换为以下字符串<ProjectReference Include=\"{packageProjectPath}\" /> 它正在用项目引用替换包
  • 我现在正在做另一个项目。一两天后,我会回来并进行验证。感谢您提供的解决方案。 :)
  • 我已经使用了这些包并且能够检索包引用。 Microsoft.Build.Utilities.Core Microsoft.Build

标签: c# .net-core nuget visual-studio-2019 projects-and-solutions


【解决方案1】:

是否有任何可用的 Microsoft nuget 包可以读取 csproj 文件中的包引用?

据我所知Microsoft.Build.Engine 不支持编辑 New Sdk 格式项目(Net Core),并且与这个 nuget 包不兼容。此 nuget 包仅适用于旧的 sdk 格式项目(Net Framework),您无法编辑 Net Core 项目的 xml 元素。

获取 .Net Core 3.1 中 csproj 中包含的 nuget 包版本

由于您想获取 Nuget 包引用及其版本,您可以通过编程方式尝试此功能:

public class PackageReference
        {
            public string Include { get; set; } //get the nuget reference name
            public Version Version { get; set; } // get thee nuget package version
        }


        static void Main(string[] args)
        {

    //load the xxx.csproj file
            var doc = XDocument.Load("C:\\xxxx\\xxxx\\xxx\\xxx\\xxx.csproj");
            var packageReferences = doc.XPathSelectElements("//PackageReference")
                .Select(pr => new PackageReference
                {
                    Include = pr.Attribute("Include").Value,
                    Version = new Version(pr.Attribute("Version").Value)
                });

            Console.WriteLine($"Project file contains {packageReferences.Count()} package references:");
            foreach (var packageReference in packageReferences)
            {
                Console.WriteLine($"{packageReference.Include}, version {packageReference.Version}");
            }


        }

更新 1

只需在网络框架项目中安装Microsoft.BuildMicrosoft.Build.Utilities.Core,然后键入这些可以在xxx.csproj 文件中设置属性,就像Build.Engine nuget 包所做的那样。

注意应该写在net framework项目中,而不是net core或者net standard项目中(会出错)。

using Microsoft.Build.Evaluation;
.......
{
    class Program
    {

        static void Main(string[] args)
        {
            var collection = new ProjectCollection();
            var project = collection.LoadProject(@"xx:\xxx\xxx\xxx.csproj");
            project.SetProperty("Test","true");

            project.Save(@"xx:\xxx\xxx\xxx.csproj");


        }
    }
}

希望对你有帮助。

【讨论】:

  • 你能不能把 Microsoft.Build.Evaluation 与 .netstandard 不兼容作为旁注。我刚刚遇到这个问题,如果使用 .netstandard2.0,您的第一个解决方案将是适用的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-14
  • 1970-01-01
  • 2020-06-07
  • 2018-10-22
  • 1970-01-01
相关资源
最近更新 更多