Skip to content

Instantly share code, notes, and snippets.

@to11mtm
Created September 18, 2024 18:29
Show Gist options
  • Save to11mtm/b51b7520c82203e2b4b92e5103dbed3b to your computer and use it in GitHub Desktop.
Save to11mtm/b51b7520c82203e2b4b92e5103dbed3b to your computer and use it in GitHub Desktop.
so gross
using System.Configuration;
using System.IO;
using Microsoft.Extensions.Configuration;
using ConfigurationBuilder = Microsoft.Extensions.Configuration.ConfigurationBuilder;
using OldConfigurationManager = System.Configuration.ConfigurationManager;
namespace JsonConfigBridge
{
public class Class1
{
// Per JBAI (Thanks btw!)
/*
* Remember that System.Configuration.ConfigurationManager.AppSettings is read-only in runtime,
* so this piece of code should be performed before any reads from ConfigurationManager.AppSettings.
* Note: It's a best practice to read configurations at the startup of your application
*/
public void derp()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
IConfiguration configuration = builder.Build();
foreach (var configurationSection in configuration.GetChildren())
{
LoadConfigToAppSettings(configurationSection,configurationSection.Key);
}
foreach (var child in configuration.GetSection("ApplicationSettings")
.GetChildren())
{
OldConfigurationManager.AppSettings[child.Key] = child.Value;
}
foreach (var cstr in configuration.GetSection("ConnectionStrings").GetChildren())
{
OldConfigurationManager.AppSettings[cstr.Key] = cstr.Value;
}
}
void LoadConfigToAppSettings(IConfigurationSection section, string parentKey = "")
{
foreach (var child in section.GetChildren())
{
var key = (string.IsNullOrEmpty(parentKey)? "" : $"{parentKey}:") + child.Key;
if (child.Value == null) // It's a section
LoadConfigToAppSettings(child, key);
else
OldConfigurationManager.AppSettings[key] = child.Value;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment