This QuickStart does not use Enterprise Library. It is intended to provide guidance to users of previous versions of the Enterprise Library Configuration Application Block on how to migrate to the new features in System.Configuration in the .NET Framework 2.0.
The Configuration functionality in the Enterprise Library Core provides services to the other blocks in the library and is not normally needed in user code.
大意是:Configuration Application Block這個模組現在已經合并到.Net 2.0 System.Configuration中了,所以EL中不再單獨保留這一模組,也就是說這部分功能完全用.net 2.0內建的功能就可實現
應用情境:有時候,我們希望把某些類能序列化儲存在app.config或web.config中,並能讀寫。
使用步驟:
1.先定義希望序列化儲存的類,注意要繼承自ConfigurationSection,範例程式碼如下:
Code
Code
using System.Configuration;
namespace ConfigTest
{
public class MyConfigClass : ConfigurationSection
{
[ConfigurationProperty("name")]
public string Name
{
get { return (string)this["name"]; }
set { this["name"] = value; }
}
[ConfigurationProperty("age")]
public int Age
{
get { return (int)this["age"]; }
set { this["age"] = value; }
}
public override string ToString()
{
return "Name=" + Name + ",Age=" + Age;
}
}
}
2.寫入配置
Code
const string SECTIONNAME = "MySettings";
private void btnWrite_Click(object sender, EventArgs e)
{
MyConfigClass _myConfig = new MyConfigClass();
_myConfig.Age = int.Parse(txtAge.Text);
_myConfig.Name = txtName.Text;
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.Sections.Remove(SECTIONNAME);
config.Sections.Add(SECTIONNAME, _myConfig);
config.Save();
}
注意:這是winform(c/s)下的代碼,如果是網站web應用,這樣是會出錯的!
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
要改成下面這樣
string _ConfigPath = Server.MapPath("web");//如果這裡web改為web.config,最終會產生一個新的web.config.config的檔案,所以這裡必須在根目錄下建立一個名為"web"(注意不帶副檔名)文字檔,然後系統才會正確寫到web.config中,能想到這招騙過系統,我太有才啦^_^
Configuration config = ConfigurationManager.OpenExeConfiguration(_ConfigPath);
3.讀取配置
Code
Code
private void btnRead_Click(object sender, EventArgs e)
{
//winform環境下,不加這一行,則永遠讀取的是緩衝中的“舊”值;webform中因為頁面重新整理的關係,不加也可以正常讀取到新的值
ConfigurationManager.RefreshSection(SECTIONNAME);
MyConfigClass configData = ConfigurationManager.GetSection(SECTIONNAME) as MyConfigClass;
if (configData != null)
{
txtRead.Text = configData.ToString();
}
else
{
txtRead.Text = SECTIONNAME + "配置節讀取失敗!";
}
}
另外當配置更改(也就是配置值被修改)時,可以利用FileSystemWatcher監聽實現觸發某一事件,詳情可見\EntLib41Src\Quick Starts\Configuration-Migration樣本程式