I'm using MSBuildWorkspace to load solution for analyze using OpenSolutionAsync and then iterating for projects. I cant see any information about nuget packages that are referenced by project. There is MetadataReferences but this is a list of dll’s with no explicit version of library - it is somewhere in path but to extract this I would have to extract it from text. Also sometimes this list is empty because some errors during project load.
Is there any way to get simple list of name and version of referenced library?
In according to this question discussion, MSBuildWorkspace
does not have any capability to get NuGet references of a project.
However you may parse .csproj file if you use project sdk format or packages.config otherwise.
For project sdk you may use the following code:
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
}
}
For old .csproj format you may use the following code:
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
}
}