Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

nuget

What's the best way to read (ideally via C#) the packages listed in packages.config files?

Within our source code repository I have a lot of solutions and projects and equally a lot of packages.config files. I'm trying to build a consolidated list of packages (and versions) in use across my source code repository.

I can see there is a NuGet.Core package available - how could I use this to achieve my goal?

Thanks

like image 506
Gary Howlett Avatar asked Oct 09 '15 10:10

Gary Howlett


People also ask

How do I get NuGet package list?

go to the Project or Solution in question. right click, Manage NuGet Packages... on the left, you will see 'Installed Packages' click on this and you will see the list.

What about NuGet packages and packages config?

The packages. config file is used in some project types to maintain the list of packages referenced by the project. This allows NuGet to easily restore the project's dependencies when the project is to be transported to a different machine, such as a build server, without all those packages.

Where is NuGet packages config?

If you right click the project in question you can select "Manage nuGet Packages" from the menu. After you do that you can click "installed packages" on the left hand side to see the packages that you currently have installed. These are what you are seeing in your "packages. config" file.

How do you check NuGet packages?

When you visit nuget.org or open the Package Manager UI in Visual Studio, you see a list of packages sorted by relevancy. This shows you the most widely used packages across all . NET projects.


1 Answers

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);
}
like image 136
Matt Ward Avatar answered Oct 11 '22 00:10

Matt Ward