How to read the list of NuGet packages in packages.config programatically?

If you do not want to read the XML directly you can install the NuGet.Core NuGet package and then use the PackageReference class.

Here is some example code that uses this class to print out the package id and its version.

string fileName = @"c:\full\path\to\packages.config";

var file = new PackageReferenceFile(fileName);
foreach (PackageReference packageReference in file.GetPackageReferences())
{
    Console.WriteLine("Id={0}, Version={1}", packageReference.Id, packageReference.Version);
}

You will need to find the packages.config files yourself which you can probably do with a directory search, something like:

foreach (string fileName in Directory.EnumerateFiles("d:\root\path", "packages.config", SearchOption.AllDirectories))
{
    // Read the packages.config file...
}

An alternative and more up to date way of doing this is to install the NuGet.Packaging NuGet package and use code similar to:

var document = XDocument.Load (fileName);
var reader = new PackagesConfigReader (document);
foreach (PackageReference package in reader.GetPackages ())
{
    Console.WriteLine (package.PackageIdentity);
}

Tags:

C#

Nuget