将自定义配置组移动到单独的文件中

24

我最近写了一个相当大的自定义配置组。我想知道是否可以通过以下方式将此配置移动到单独的文件中:

<configuration>
    <configSections>
        <sectionGroup name="MyCustomGroup">
            <section name="MyCustomSection"/>
        </sectionGroup>
    </configSections>
    <MyCustomGroup file="alt.config" />
</configuration>

这类似于你可以使用appSettings的file属性所做的操作。我意识到我的自定义部分处理程序可能需要创建ConfigurationPropertyAttribute,但是在这方面我一直没有找到任何示例或指导。

1个回答

38
据我所知,您无法使用configSource属性来外部化整个SectionGroup(即MyCustomGroup),而是必须在Section级别上处理此问题(即MyCustomSection)。

<configuration>
    <configSections>
        <sectionGroup name="MyCustomGroup">
                <section name="MyCustomSection"/>
        </sectionGroup>
    </configSections>
    <MyCustomGroup>    
       <MyCustomSection configSource="externalfile.config" />
    </MyCustomGroup>
</configuration>

外部文件externalfile.config将包含您的实际配置设置,直接以自定义部分标记开头(无需<?xml....?><configuration>或任何其他内容):

<MyCustomSection>
    ... your settings here......
</MyCustomSection>

Marc


1
你是正确的。章节组不能作为一个整体外部化,但它的各个章节可以。 - Erik Schierboom
@marc_s - 太好了,我没有意识到这是一个如此古老的问题。我只是在谷歌上搜索,发现这是最顶部的结果! - Liath
2
正是我所需要的。 - Anton Skovorodko

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接