Lee Crabtree
Lee Crabtree

Reputation: 1256

Can I change the default config file?

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?

Upvotes: 3

Views: 912

Answers (2)

tvanfosson
tvanfosson

Reputation: 532455

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 = configDoc.Descendants( "sectionName" ).First();

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

Upvotes: 0

Charles Bretana
Charles Bretana

Reputation: 146499

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));
        }
    }

Upvotes: 5

Related Questions