Net有道

紫冠道人的求道历程

导航

RFID会议签到系统总结(六)――系统配置(下)

 

关于读配置,上次还漏说了一种情况,就是配置文件不是通常的由app.config生成的,其名字与程序集名字不相关的的时候,我们得自己写类似于GetConfig的方法来读取。这个种时候与写配置文件的功能有相通之处,所以放在这一篇里讲。

先来个读写配置文件的基类ConfigIOBase

读写配置文件的基类

 

这里其实没什么奥秘,就是一些XML方面的读取,从name读到type名,然后利用反射创建Handler,然后就可以进行下面的处理。

比如读取配置,就可以如下面这样了

       public object GetConfig(string sectionName)

       {

           CustomSectionHandlerBase handler = getHandler(sectionName);

           if (handler != null)

           {

              return handler.Create(null,null,cfgSection.SelectSingleNode("//" + sectionName));

           }

           return null;

       }

.Net Framework里的GetConfig方法其实也是如上述这样做的。而写配置则纯粹就是用有关XML的操作的。

       /// <summary>

       /// 写配置节

       /// </summary>

       /// <param name="sectionName">节名</param>

       /// <param name="sectionValue">要写的内容</param>

       public void Write(string sectionName,object sectionValue){

           CustomSectionHandlerBase handler = getHandler(sectionName);

           if (handler != null){

              try{

                  XmlNode writeData = handler.SetSection(sectionValue);

                  XmlNode repData = doc.ImportNode(writeData,true);

                  cfgSection.ReplaceChild(repData,cfgSection.SelectSingleNode("//" + sectionName));

              }catch(Exception){

              }

           }

       }


Handler
SetSection方法在上一篇里有说明。

最后不要忘了保存文件,

public void Save(){

           if ((File.GetAttributes(configPath) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly){

              File.SetAttributes(configPath,FileAttributes.Normal);

           }

           doc.Save(configPath);

       }

 

系统开发中在设计阶段不可能面面倶到,在实现阶段有时不得不新增一些配置,但又不想去为此兴师动众的新增配置类、新增handler,而且还得修改配置文件顶部,还不如在appSettings里新增一项来得方便,为了方便写appSettings节,后来在写配置文件的类里又新增一个写方法

       public void WriteAppSettings(string itemName,string itemValue)

       {

           XmlNode appSection = cfgSection.SelectSingleNode("//appSettings/add[@key='" + itemName + "']");

           if (appSection != null)

           {

              XmlAttribute valueAttribute = appSection.Attributes["value"];

              valueAttribute.Value = itemValue;

           }

       }

 

至此,有关系统配置的管理基础设施完成,接下来要做的只是做些可以用来设置数据库连接、设置管控端地址等变量的窗体,在这些窗体的代码你将可以用一个个的类来操作你的配置。优势更为明显的地方在于硬件配置、菜单、工具栏配置这些带有集合性质的地方,到时我们面对的不再是一串串的XML,而是一个个的list,操作起来极其的方便,大大减少程序实现中出现的一些低级错误。

posted on 2007-06-14 14:36  lichdr  阅读(632)  评论(1编辑  收藏  举报