How do I get the values from a ConfigSection defined as NameValueSectionHandler when using ConfigurationManager.OpenMappedExeConfiguration

心已入冬 提交于 2019-12-01 05:51:20
JJS

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!