Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load multiple config files in .Net Core

I want to load multiple config files from a folder in a loop in .Net core middle ware.

I know we can load one or multiple config files by naming them like appSettings.json as mentioned here

But in my case, if I have multiple config folders, and each folder has multiple config files to be loaded initially. And If I start naming each file in each folder to load, it will be lot of lines and messier. I am looking to load all of the config folders in loop.

Please ask if need more info. Thanks

like image 787
Syed Avatar asked May 23 '18 11:05

Syed


People also ask

Can we have multiple config files?

You can have multiple configuration files in your asp.net project. There is no restriction to use the web. config file in the asp.net web application. You can have 1 Web.

Can I add more than two Appsettings json files in dotnet core?

Can I add more than two appsettings. json files in dotnet core? Of course, we can add and use multiple appsettings. json files in ASP.NET Core project.

Can we have multiple config file for single project?

Yes you can have two web. config files in application. There are situations where your application is divided in to modules and for every module you need separate configuration.


2 Answers

You can achieve this using something like Directory.EnumerateFiles and ConfigureAppConfiguration. Here's an example of what this might look like:

WebHost.CreateDefaultBuilder(args)
    .UseStartup<Startup>()
    .ConfigureAppConfiguration(configurationBuilder =>
    {
        foreach (var jsonFilename in Directory.EnumerateFiles("/path/to/jsons", "*.json", SearchOption.AllDirectories))
            configurationBuilder.AddJsonFile(jsonFilename);
    })
    .Build();

The call to ConfigureAppConfiguration allows for adding additional providers to the configuration system. Here, we're just adding all *.json files found within the /path/to/jsons directory (and children) as additional configuration sources.

like image 194
Kirk Larkin Avatar answered Oct 19 '22 11:10

Kirk Larkin


Well, i had to figure out it with an extension method to the ConfigurationBuilder class. Hope it helps to anybody in need.

 public static IConfigurationBuilder AddMultipleJsonFiles(this IConfigurationBuilder configurationBuilder, string path, string prefix)
    {
        string[] files = System.IO.Directory.GetFiles(path, prefix + "-*.json");

        foreach (var item in files)
        {
            configurationBuilder.AddJsonFile(item);
        }
        return configurationBuilder;
    }

And also;

 var builder = new ConfigurationBuilder().AddMultipleJsonFiles(Directory.GetCurrentDirectory()+ "/Configurations/", "service");
            _configuration = builder.Build();
like image 5
MonkeyDLuffy Avatar answered Oct 19 '22 10:10

MonkeyDLuffy