Reputation: 934
I have a console application that scans for duplicate or out of date nuget packages. When the packages were located in packages.config I could use this code
var packageReferences = new PackagesConfigReader(
new FileStream(path, FileMode.Open, FileAccess.Read))
.GetPackages();
return packageReferences;
To read them and get back IEnumerabla. I'm trying to make it work with CSPROJ files, but the above does not work any more, and I can't seem to find any documentation on how to read it (other than manually loading the XML).
Is there a way to make it work with CSPROJ files ?
Upvotes: 1
Views: 1686
Reputation: 4057
I suggest parsing the XML. I created this in two minutes.
void Main()
{
var xml = @"<Project Sdk=""Microsoft.NET.Sdk.Web"">
<PropertyGroup>
<TargetFramework>net47</TargetFramework>
<OutputType>Exe</OutputType>
<GenerateAssemblyTitleAttribute>true</GenerateAssemblyTitleAttribute>
<GenerateAssemblyDescriptionAttribute>true</GenerateAssemblyDescriptionAttribute>
</PropertyGroup>
<ItemGroup>
<PackageReference Include=""Microsoft.AspNetCore"" Version=""2.1.2"" />
<PackageReference Include=""Microsoft.AspNetCore.Authentication.Cookies"" Version=""2.1.1"" />
<PackageReference Include=""Microsoft.AspNetCore.Authentication.JwtBearer"" Version=""2.1.1"" />
</ItemGroup>
</Project>";
var doc = XDocument.Parse(xml);
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}");
}
// Output:
// Project file contains 3 package references:
// Microsoft.AspNetCore, version 2.1.2
// Microsoft.AspNetCore.Authentication.Cookies, version 2.1.1
// Microsoft.AspNetCore.Authentication.JwtBearer, version 2.1.1
}
public class PackageReference
{
public string Include { get; set; }
public Version Version { get; set; }
}
Upvotes: 4