如何使用 MSBuildWorkspace 获取引用的 nuget 包?

How to get referenced nuget packages using MSBuildWorkspace?

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

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

根据 this question discussionMSBuildWorkspace 无法获取项目的 NuGet 引用。 但是,如果您使用项目 sdk 格式,则可以解析 .csproj 文件,否则 packages.config。

对于项目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
    }
}