IConfigurationSectionHandler を使うと Web.Config に簡単に独自の設定を追加することができます。
MyConfig クラス
using System;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
namespace WebApplication1
{ [Serializable]
public class MyConfig : IConfigurationSectionHandler
{ public object Create(object parent, object configContext, System.Xml.XmlNode section)
{ XmlSerializer ser = new XmlSerializer(this.GetType());
return ser.Deserialize(new XmlNodeReader(section));
}
public MyConfig()
{ }
public static MyConfig Instance()
{ return (MyConfig)ConfigurationSettings.GetConfig("MyConfig"); }
private string _strParam = "*"; // default: "*"
public string StrParam
{ get { return _strParam; } set { _strParam = value; } }
private bool _boolParam = true; // default: true
public bool BoolParam
{ get { return _boolParam; } set { _boolParam = value; } }
private int _intParam = 10; // default: 10
public int IntParam
{ get { return _intParam; } set { _intParam = value; } }
}
}
Web.config
<configuration>
<configSections>
<section name="MyConfig" type="WebApplication1.MyConfig, WebApplication1"/>
</configSections>
<MyConfig>
<StrParam>abc</StrParam>
<BoolParam>false</BoolParam>
<IntParam>5</IntParam>
</MyConfig>
</configuration>
こういう風にしておくと読み込みの際に MyConfig.Create が呼ばれるので XmlSerializer を使ってデシリアライズしてあげるわけです。
使うときはこんな感じ
Label1.Text = MyConfig.Instance().StrParam;
Label2.Text = MyConfig.Instance().BoolParam.ToString();
Label2.Text = MyConfig.Instance().IntParam.ToString();
ちなみにデシリアライズされた結果はキャッシュされているようで MyConfig.Instance() するたびにデシリアライズが実行されるということはありません。
あと、たとえば int 型の項目に "abc" とかって指定するとデシリアライズ時に例外が発生するのでエラーページが表示されることになります。