我可以更改默认配置文件吗?

时间:2009-01-07 17:12:48

标签: c# .net

我正在使用Jeff Atwood的Last Configuration Section Handler You'll Ever Need,但它似乎只适用于默认的app.config文件。如果我想将某些设置分成另一个文件,则反序列化不起作用,因为ConfigurationManager.GetSection只从应用程序的默认app.config文件中读取。是否可以更改默认配置文件的路径或将ConfigurationManager指向第二个配置文件?

2 个答案:

答案 0 :(得分:5)

是的,只需将默认配置文件中的部分替换为具有指向另一个文件的configSource =“”属性的同名xml元素......

...在App.config或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" />

然后是常见的xml; 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));
        }
    }

答案 1 :(得分:0)

您可以手动执行此操作,方法是将文档作为XDocument打开,找到相应的部分并将其传递给配置部分处理程序。

XDocument configDoc = XDocument.Load( alternateConfigFile );

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

var obj = sectionHandler.Create( null, null, section );
相关问题