园子里TerryLee的Enterprise Library系列文章回顾与总结 http://www.cnblogs.com/Terrylee/archive/2006/08/01/464591.html已经写得很全面了,不过不是针对4.1版,一边看这一系列的文章学习,一边在4.1上摸索,准备写几篇学习笔记,今天先来认识Configuration Application Block(配置应用程序块)
参照TerryLee的文章,在4.1上怎么也找不到Configuration Application Block,相信很多人也跟我一样晕吧? 呵呵
无奈之下,打开\EntLib41Src\Quick Starts\Configuration-Migration\CS 运行了下,恍然大悟!
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,示例代码如下:
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.写入配置
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();
}
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 + "配置节读取失败!";
}
}