zoukankan      html  css  js  c++  java
  • Win Form 项目中app.config读取和修改 [ZT]

    看到网上的读写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是在程序启动时就载入的,修改后的值要重新运行程序后才能读到。

  • 相关阅读:
    RabbitMQ安装与配置
    在Web项目中使用shiro
    solr整合spring
    mycat
    SpringSession管理
    Nginx安装与配置(Nginx服务器和Tomcat服务器是不同的服务器)
    dubbo负载均衡与服务降级以及Zookeeper认证
    小笔记
    SpringMVC路径转发与重定向
    java-同步控制及不可变设置(只读访问)
  • 原文地址:https://www.cnblogs.com/dxz/p/winform_appconfig_modify.html
Copyright © 2011-2022 走看看