参照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.写入配置
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.读取配置
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示例程序