Getting the values from a config file that uses a section defined by System.Configuration.NameValueSectionHandler is easy when you\'re using the current config file for the
I ran across my own answer from two years ago.
NameValueSectionHandler - can i use this section type for writing back to the application config file?
This is my approach to solve my current issue.
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap() {
ExeConfigFilename = "path to config here"
};
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(
configFileMap, ConfigurationUserLevel.None);
ConfigurationSection myParamsSection = config.GetSection("MyParams");
string myParamsSectionRawXml = myParamsSection .SectionInformation.GetRawXml();
XmlDocument sectionXmlDoc = new XmlDocument();
sectionXmlDoc.Load(new StringReader(myParamsSectionRawXml ));
NameValueSectionHandler handler = new NameValueSectionHandler();
NameValueCollection handlerCreatedCollection =
handler.Create(null, null, sectionXmlDoc.DocumentElement) as NameValueCollection;
Console.WriteLine(handlerCreatedCollection.Count);
A method that works with any of the legacy IConfigurationSectionHandler types NameValueSectionHandler, DictionarySectionHandler, SingleTagSectionHandler.
public static object GetConfigurationValues(string configFileName, string sectionName)
{
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap() { ExeConfigFilename = configFileName };
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
ConfigurationSection section = config.GetSection(sectionName);
string xml = section.SectionInformation.GetRawXml();
XmlDocument doc = new XmlDocument();
doc.Load(XmlReader.Create(new StringReader(xml)));
string type = section.SectionInformation.Type;
string assemblyName = typeof(IConfigurationSectionHandler).Assembly.GetName().FullName;
ObjectHandle configSectionHandlerHandle = Activator.CreateInstance(assemblyName, section.SectionInformation.Type);
if (configSectionHandlerHandle != null)
{
IConfigurationSectionHandler handler = configSectionHandlerHandle.Unwrap() as IConfigurationSectionHandler;
return handler.Create(null, null, doc.DocumentElement);
}
return null;
}