园子里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,示例代码如下:

 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.读取配置
;
            }

        }
另外当配置更改(也就是配置值被修改)时,可以利用FileSystemWatcher监听实现触发某一事件,详情可见\EntLib41Src\Quick Starts\Configuration-Migration示例程序

相关文章:

  • 2022-12-23
  • 2022-03-06
  • 2021-05-28
  • 2021-10-14
  • 2022-12-23
  • 2021-11-29
  • 2021-12-11
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-08-10
  • 2022-01-26
  • 2022-01-02
  • 2021-09-02
  • 2021-08-03
相关资源
相似解决方案