Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read nuget.config programmatically in c#

Is it possible to read nuget.config file and packages sources inside with using Nuget.visualStudio,nuget.core or nuget.clients dll.I can parse xml but is there any outofthebox logic in nuget.dlls

like image 216
Bilgehan Avatar asked Oct 20 '25 06:10

Bilgehan


1 Answers

Yes! You need to consume the NuGet.Configuration package available at https://www.nuget.org/packages/NuGet.Configuration/4.6.2.

Then you can use the following code -

using NuGet.Configuration;
using System;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // basic implementation of nuget.config in code
            var setting = Settings.LoadSpecificSettings(@"f:\root", "nuget.config");

            // get sources 
            var packageSourceProvider = new PackageSourceProvider(setting);
            var sources = packageSourceProvider.LoadPackageSources();

            foreach(var source in sources)
            {
                Console.WriteLine($"{source.Name}: {source.SourceUri}");
            }
        }
    }
}

This will generate the following output -

NuGet.org: https://api.nuget.org/v3/index.json

Sample config file used (lets say at path f:\root\nuget.config)-

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="NuGet.org" value="https://api.nuget.org/v3/index.json" />
  </packageSources>
</configuration>
like image 149
Ankit Mishra Avatar answered Oct 22 '25 03:10

Ankit Mishra