动态读取App.Config

关于APP.CONFIG

      在做Winform开发时,免不了把一些配置信息写到APP.CONFIG文件中,当程序生成后APP.CONFIG会变成以程序名+CONFIG的文件
即,如程序名为A,那么生成后的APP.CONFIG文件会变成A.EXE.CONFIG文件!

正文
      以偶在做项目为例.程序要根据用户设定的时间,自动检查OUTLOOK的"垃圾邮件箱"垃圾邮件.!偶把设定后的时间保存在了APP.CONFIG中
用户设定后再重新读取值显示到界面上,用的方法:ConfigurationSettings.AppSettings,结果发现没有读到.后来才明白,原来CONFIG文件只在程序初次运行才读取值.如果在程序运行中,改变其值然后读取,其实读的是缓存的文件.并不是CONFIG文件本身.如果想动态读取就要用XML的读方法
下面是偶写的一个方法,没啥技术含量,在此记下方便日后查询!

/// <summary>
/// Read confing
/// </summary>
/// <param name="path"></param>
/// <param name="appKey"></param>
/// <returns></returns>

public string GetConfigValue(string path,string appKey)  
{     
  XmlDocument xDoc 
= new XmlDocument();     
  
try
   
{
     xDoc.Load(path);     
    
//xDoc.Load(System.Windows.Forms.Application.ExecutablePath+".config");
    XmlNode xNode;     
    XmlElement xElem;     
    xNode 
= xDoc.SelectSingleNode("//appSettings");    
    xElem 
= (XmlElement)xNode.SelectSingleNode("//add[@key='"+appKey+"']");     
    
if(xElem!=null)   
     
return xElem.GetAttribute("value");     
    
else     
     
return   "";
   }

 
catch(Exception)
   
{
     
return "";
   }

}
 
posted @ 2007-03-19 16:23  孙英雄  阅读(13139)  评论(12编辑  收藏  举报