アプリケーション構成ファイルの小ネタ

アプリケーション構成ファイルには、ユーザ固有の設定を定義する場所として「appSettings」要素があるが、アプリケーションの規模が大きくなるとこの部分が膨れ上がって、管理しずらくなる。
これを解消する手段として、この設定を外部ファイル化できる。

通常は以下のように記述する。

<configuration>
    <appSettings>
        <add key="name" value="Hoge" />
    </appSettings>
</configuration>

「appSettings」の内容を切り出したXMLファイルを作成する。(例:Hoge.xml

<?xml version="1.0" encoding="shift-jis"?>
<appSettings>
    <add key="name" value="Hoge" />
</appSettings>

「file」属性で、外部ファイルを指定する。

<configuration>
    <appSettings file="hoge.xml">
    </appSettings>
</configuration>

これで「appSettings」の内容を外部ファイルに切り出す事ができる。
この時、外部ファイルのルート要素は「appSettings」である必要があるけど、独自のタグにしたい場合は以下のようにする。

新しい構成セクションを宣言して、型を「System.Configuration.NameValueSectionHandler」にすると。
独自タグで「file」属性を指定して、外部ファイルを設定することができる。

<configuration>
    <configSections>
        <section name="properties" type="System.Configuration.NameValueFileSectionHandler" />
    </configSections>

    <properties file="Hoge.xml">
    </properties>
</configuration>

以下、「Hoge.xml」の内容

<?xml version="1.0" encoding="shift-jis"?>
<properties>
    <add key="name" value="Hoge" />
</properties>