Can I change the default configuration file?

I use Jeff Atwood. The last configuration section handler you will ever need , but it only works for the default application. configuration file. If I wanted to separate certain settings in another file, deserialization would not work, as ConfigurationManager.GetSection would only read from the app.config file by default of the application. Is it possible to change the path to the default configuration file or specify ConfigurationManager in the second configuration file?

+3
source share
2 answers

yes, just replace the section in the default configuration file with an xml element with the same name that has the configSource = "" attribute that points to another file ...

... in yr App.config or web.config ...

  <configSections>
      <section name="Connections"
         type="BPA.AMP.Configuration.XmlConfigurator, BPA.AMP.Data.Config.DAL"/>
      <section name="AutoProcessConfig"
         type="BPA.AMP.Configuration.XmlConfigurator, BPA.AMP.Data.Config.DAL"/>
  </configSections>


  <Connections configSource="Config\Connections.config" />
  <AutoProcessConfig configSource="Config\AutoProcess.config" />

And then the general xml class; Configurator

   public class XmlConfigurator : IConfigurationSectionHandler
    {
        public object Create(object parent, 
                          object configContext, XmlNode section)
        {
            XPathNavigator xPN;
            if (section == null || (xPN = section.CreateNavigator()) == null ) 
                 return null;
            // ---------------------------------------------------------
            Type sectionType = Type.GetType((string)xPN.Evaluate
                                    ("string(@configType)"));
            XmlSerializer xs = new XmlSerializer(sectionType);
            return xs.Deserialize(new XmlNodeReader(section));
        }
    }
+5
source

You can do this manually by opening the document as an XDocument, finding the appropriate section and passing it to the configuration section handler.

XDocument configDoc = XDocument.Load( alternateConfigFile );

var section = configDoc.Descendants( "sectionName" ).First();

var obj = sectionHandler.Create( null, null, section );
0
source

All Articles