I solved a similar problem where I wanted to associate the entire IConfigurationRoot or IConfigurationSection with the Dictionary. Here is the extension class:
public class ConfigurationExtensions { public static Dictionary<string, string> ToDictionary(this IConfiguration config, bool stripSectionPath = true) { var data = new Dictionary<string, string>(); var section = stripSectionPath ? config as IConfigurationSection : null; ConvertToDictionary(config, data, section); return data; } static void ConvertToDictionary(IConfiguration config, Dictionary<string, string> data = null, IConfigurationSection top = null) { if (data == null) data = new Dictionary<string, string>(); var children = config.GetChildren(); foreach (var child in children) { if (child.Value == null) { ConvertToDictionary(config.GetSection(child.Key), data); continue; } var key = top != null ? child.Path.Substring(top.Path.Length + 1) : child.Path; data[key] = child.Value; } } }
And using the extension:
IConfigurationRoot config; var data = config.ToDictionary(); var data = config.GetSection("CustomSection").ToDictionary();
There is an optional parameter (stripSectionPath) to either save the full path of the section key or cut out the section path, leaving the relative path.
var data = config.GetSection("CustomSection").ToDictionary(false);
Michal steyn
source share