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

  • 相关阅读:
    2019年年终总结
    [转]网络基本功08-细说TCP滑动窗口
    anaconda启动报错-pythonw.exe
    FRP+WoL实现远程开机+远程桌面
    [转]网络基本功06-链路聚合
    我的效率工具分享
    比海飞丝更柔顺的写作体验
    阿里云加Picgo或MPic搭建最豪横的图床
    markdown从入门到放弃word和PDF
    Pocket+Evernote 打造个人知识库体系
  • 原文地址:https://www.cnblogs.com/dxz/p/winform_appconfig_modify.html
Copyright © 2011-2022 走看看