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

前端 未结 1 1296
挽巷
挽巷 2021-01-13 00:02

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

相关标签:
1条回答
  • 2021-01-13 01:07

    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;
    }
    
    0 讨论(0)
提交回复
热议问题