tags:

views:

278

answers:

2

I'm using Jeff Atwood's Last Configuration Section Handler You'll Ever Need, but it only seems to work for the default app.config file. If I wanted to separate certain settings into another file, the deserializing doesn't work, since ConfigurationManager.GetSection only reads from the application's default app.config file. Is it possible to either change path of the default config file or point ConfigurationManager to a second config file?

+4  A: 

yes, just replace the section in the default config file with an xml element of the same name that has a 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 common xml;Configurator class

   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));
        }
    }
Charles Bretana
Bless you, my son. That is totally and completely badass.
Lee Crabtree
Yr totally, like, welcome, dude!
Charles Bretana
A: 

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

XDocument configDoc = XDocument.Load( alternateConfigFile );

var section = from s in configDoc.Descendants( "sectionName" ) select s;

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