技術をかじる猫

適当に気になった技術や言語、思ったこと考えた事など。

何か色々 appConfig 設定ファイル .NET 2.0 var

.NET 2.0 以上で取り出し方。

System.Configration.dll をライブラリ参照に加えて、以下のコード。

System.Configuration.ConfigurationManager.AppSettings["sample"];
(MyConfig)System.Configuration.ConfigurationManager.GetSection("MyConfig");

何が違うのかわからん。

設定ファイルに書き込み、読み込み。

CS ファイルに以下のをごりごりと。

public class MyConfig : ApplicationSettingsBase
{
    [UserScopedSetting]
    public string StrParam
    {
        get { return (String)this["StrParam"]; }
        set { this["StrParam"] = value; }
    }
}

使うのは気楽に。

MyCondig conf = new MyConfig();
conf.StrParam = "HAHAHA";
conf.Save();

読み込みはそのまま。
アプリケーションスコープの設定は、アプリケーション毎の設定で、すべてのユーザーで同じ設定が使用される。また、基本的にはread only。
アプリケーションスコープの設定は、アプリケーション構成ファイルに保存。

ユーザースコープの設定は、ユーザー毎の設定で、read, write 可。
保存される設定は、非ローミングユーザーのアプリケーションデータフォルダに、user.configという名前のXMLファイルとして書き込む。*1

ConfigurationSection 経由

こんな設定に対して。

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <sectionGroup name="customConfig">
      <section name="myConfig" type="SqlProviderSetting.MyConfig, SqlProviderSetting"
               allowDefinition="Everywhere" allowLocation="true"/>
    </sectionGroup>
  </configSections>

  <customConfig>
    <myConfig strParam="Hello Message">
      <childSection child="Child value." />
    </myConfig>
  </customConfig>
</configuration>

こんなコードをごりごりと。

public class MyConfig : ConfigurationSection
{
    [ConfigurationProperty("strParam")]
    public String StrParam
    {
        get
        { return (String)this["strParam"]; }
        set
        { this["strParam"] = value; }
    }

    [ConfigurationProperty("childSection")]
    public MyChildConfigElement ChildSection
    {
        get
        { return (MyChildConfigElement)this["childSection"]; }
        set
        { this["childSection"] = value; }
    }
}

public class MyChildConfigElement : ConfigurationElement
{
    [ConfigurationProperty("child")]
    public String Child
    {
        get
        { return (String)this["child"]; }
        set
        { this["child"] = value; }
    }
}

実際の読み込みはこんな感じで。

MyConfig config = (MyConfig)ConfigurationManager.GetSection("customConfig/myConfig");

Console.WriteLine(config.StrParam);
Console.WriteLine(config.ChildSection.Child);

attribute 経由になった分多少マシになった感じがするけど、正直どっちでもいい気がする。
IConfigurationSectionHandler と比べてさしてかわらんよなぁ。

*1:「C:\Documents and Settings\UserName\Local Settings\Application Data\CompanyName\(appdomainname)_(eid)_(hash)\1.0.0.0\user.config」こんなん知らんよ。