normalian blog

Let's talk about Microsoft Azure, ASP.NET and Java!

皆さんが大好きな Visual Studio 上で開発するプロジェクトの設定ファイル"App.config"ファイルの中身を読み取る大作戦!

  • 注意点
    • App.configファイル内の"configSections"タグは一ファイルに一つしか定義してはいけない。また、configurationタグの直下でなくてはならない。
    • configSectionsタグのtype属性は名前空間まで含めたフルパス指定
  • 具体的な手順
    • プロジェクトを右クリック→[追加(D)]→新しい項目を追加→[Visual C#アイテム]の[アプリケーション構成ファイル]を選択
    • 以下の設定ファイルを記述する
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="Branch" type="LogPj01.Branch,LogPj01"/>
  </configSections>
  <appSettings>
    <add key="Application Name" value="MyApplication"/>
    <add key="Application Version" value="1.0.0.0"/>
    <add key="Comment" value="Hoge Hoge"/>
  </appSettings>
  <Branch branchName="test01" branchManager="test02" />
</configuration>
    • 以下のクラスを作成する
    public class Branch : ConfigurationSection
    {
        public Branch() { }

        [ConfigurationProperty("branchName")]
        public string BranchName
        {
            get
            {
                return (string)this["branchName"];
            }
        }
        [ConfigurationProperty("branchManager")]
        public string BranchManager
        {
            get
            {
                return (string)this["branchManager"];
            }
        }
    }