我正在使用 MSBuildWorkspace 加载解决方案,以便使用 OpenSolutionAsync 进行分析,然后迭代项目。我看不到项目引用的 nuget 包的任何信息。有 MetadataReferences,但这是一个 dll 列表,没有显式版本的库 - 它位于路径中的某个位置,但要提取它,我必须从文本中提取它。有时此列表为空,因为项目加载期间出现一些错误。
有没有办法获得引用库的名称和版本的简单列表?
最佳答案
根据this question discussion ,MSBuildWorkspace
没有任何能力获取项目的 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
}
}
关于.net - 如何使用MSBuildWorkspace获取引用的nuget包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58252179/