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

  • 相关阅读:
    VMware下ubuntu与win8共享文件时/mnt/hgfs目录为空的解决办法
    Flex Array内置排序方法的使用
    Flex 选项卡加载方式简介
    Flash Builder 4.6 基本设置
    Flash Builder 4.6 找不到所需的Adobe Flash Player
    2 python--工具pycharm
    1 python--安装
    安装aix补丁包
    python_day02 上节课知识点回顾
    vue组件局部与全局注册的区别
  • 原文地址:https://www.cnblogs.com/dxz/p/winform_appconfig_modify.html
Copyright © 2011-2022 走看看