【问题标题】:How to get referenced nuget packages using MSBuildWorkspace?如何使用 MSBuildWorkspace 获取引用的 nuget 包?
【发布时间】:2019-10-05 20:40:42
【问题描述】:

我正在使用 MSBuildWorkspace 加载解决方案,以便使用 OpenSolutionAsync 进行分析,然后对项目进行迭代。我看不到有关项目引用的 nuget 包的任何信息。有 MetadataReferences 但这是一个没有明确版本库的 dll 列表 - 它位于路径中的某个位置,但要提取它,我必须从文本中提取它。有时这个列表也是空的,因为项目加载过程中出现了一些错误。

有没有什么方法可以得到引用库的名称和版本的简单列表?

【问题讨论】:

    标签: .net msbuild roslyn packagereference


    【解决方案1】:

    根据this question discussionMSBuildWorkspace 没有任何能力获取项目的 NuGet 引用。 但是,如果您使用项目 sdk 格式或 packages.config,则可以解析 .csproj 文件。

    对于项目 sdk,您可以使用以下代码:

    void NugetPackages(Microsoft.CodeAnalysis.Project project)
    {
        var csproj = new XmlDocument();
        csproj.Load(project.FilePath);
        var nodes = csproj.SelectNodes("//PackageReference[@Include and @Version]");
        foreach (XmlNode packageReference in nodes)
        {
            var packageName = packageReference.Attributes["Include"].Value;
            var packageVersion = Version.Parse(packageReference.Attributes["Version"].Value);
            // handle package
        }
    }
    

    对于旧的 .csproj 格式,您可以使用以下代码:

    void NugetPackages(Microsoft.CodeAnalysis.Project project)
    {
        var directory = Path.GetDirectoryName(project.FilePath);
        var packagesConfigPath = Path.Combine(directory, "packages.config");
        var packagesConfig = new XmlDocument();
        packagesConfig.Load(packagesConfigPath);
        var nodes = packagesConfig.SelectNodes("//package[@id and @version]");
        foreach (XmlNode packageReference in nodes)
        {
            var packageName = packageReference.Attributes["id"].Value;
            var packageVersion = Version.Parse(packageReference.Attributes["version"].Value);
            // handle package
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多