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
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? Of course, we can add and use multiple appsettings. json files in ASP.NET Core 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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With