Win Form 项目中app.config读取和修改

看到网上的读写app.config的代码,说是写的时候不能直接用System.Configuration.ConfigurationSettings.AppSettings.Set(AppKey, AppValue),而要把app.config当作XML文件来写。试了下确实如此,那这个Set()方法提供来是干嘛的?源代码的SelectSingleNode()里写的XPath有问题,就随带看了点XPath基础,修改后如下:

        //读 Config
        public static string GetCfgValue(string AppKey)
        
{
            
try
            
{
                
return System.Configuration.ConfigurationSettings.AppSettings.Get(AppKey);
            }

            
catch (Exception err)
            
{
                
throw err;
            }

        }


        
//写,引入 System.XML
        public static void SetCfgValue(string AppKey, string AppValue)
        
{
            System.Xml.XmlDocument xDoc 
= new XmlDocument();
            xDoc.Load(System.Windows.Forms.Application.ExecutablePath 
+ ".config");

            XmlNode xNode;
            XmlElement xElemKey;
            XmlElement xElemValue;

            xNode 
= xDoc.SelectSingleNode("//appSettings");

            xElemKey 
= (XmlElement)xNode.SelectSingleNode("//add[@key=\"" + AppKey + "\"]");
            
if (xElemKey != null) xElemKey.SetAttribute("value", AppValue);
            
else
            
{
                xElemValue 
= xDoc.CreateElement("add");
                xElemValue.SetAttribute(
"key", AppKey);
                xElemValue.SetAttribute(
"value", AppValue);
                xNode.AppendChild(xElemValue);
            }

            xDoc.Save(System.Windows.Forms.Application.ExecutablePath 
+ ".config");
        }

PS:估计app.config是在程序启动时就载入的,修改后的值要重新运行程序后才能读到。

posted on 2007-11-24 20:09  J-Pei  阅读(1867)  评论(2编辑  收藏  举报

导航