【问题标题】:Can I change the default config file?我可以更改默认配置文件吗?
【发布时间】:2009-01-07 17:12:48
【问题描述】:

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

【问题讨论】:

    标签: c# .net


    【解决方案1】:

    是的,只需将默认配置文件中的部分替换为具有指向另一个文件的 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));
            }
        }
    

    【讨论】:

    • 祝福你,我的儿子。这完全是坏蛋。
    【解决方案2】:

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

    XDocument configDoc = XDocument.Load( alternateConfigFile );
    
    var section = configDoc.Descendants( "sectionName" ).First();
    
    var obj = sectionHandler.Create( null, null, section );
    

    【讨论】:

    • 是否还需要 LINQ 查询?它不应该返回与configDoc.Descendants("sectionName") 完全相同的结果吗?
    • @bamccaig - 我第一次学习 LINQ 时的神器,我已经更新了。
    猜你喜欢
    • 2018-08-29
    • 2016-06-10
    • 1970-01-01
    • 2013-12-16
    • 1970-01-01
    • 2013-10-11
    • 1970-01-01
    • 2012-08-16
    • 1970-01-01
    相关资源
    最近更新 更多