zoukankan      html  css  js  c++  java
  • winform程序读取和改写配置文件App.config元素的值

    winform程序读取和改写配置文件App.config元素的值

    2016-05-16 17:49 by newbirth, 2412 阅读, 0 评论, 收藏编辑

    1
    2
    3
    4
    5
    6
    7
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <appSettings>
        <!--图片存放路径-->
        <add key="ImgPath" value="D:img" />
      </appSettings>
    </configuration>

      

     

           可以看出,app.config和web.config一样,嗯,它也是一个XML文件。那怎么对这个文件中的元素进行读取操作呢?很简单,来看代码:

    string strPath = System.Configuration.ConfigurationSettings.AppSettings["ImgPath"].ToString();

           这样就可以把app.config文件中ImgPath这个元素的Value值读取出来了。那怎么改写元素的值呢?如果你认为像读那样的去写,像这样的代码:

    System.Configuration.ConfigurationSettings.AppSettings["ImgPath"] = @"E:img"; //这样写是没用的

           在对app.config文件的元素Value值进行修改操作时,只能把app.config文件当作一个普通的XML文件来对待,利用System.Xml.XmlDocument类把这个app.config文件读到内存中,并通过System.Xml.XmlNode类找到appSettings节点,通过System.Xml.XmlElement类找到节点下的某个元素,利用SetAttribute方法来修改这个元素的值后,最后再将app.config文件保存到原的目录中,这样,才算完成了对一个元素Value值的修改操作。下面这个方法可完成对app.config文件appSettings节点下任意一个元素进行修改,当然,你也可能修改这个方法,达到修改任意节点,任意元素的Value值。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    public static void SetValue(string AppKey, string AppValue)
            {
                System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
                xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");
     
                System.Xml.XmlNode xNode;
                System.Xml.XmlElement xElem1;
                System.Xml.XmlElement xElem2;
                xNode = xDoc.SelectSingleNode("//appSettings");
     
                xElem1 = (System.Xml.XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']");
                if (xElem1 != null) xElem1.SetAttribute("value", AppValue);
                else
                {
                    xElem2 = xDoc.CreateElement("add");
                    xElem2.SetAttribute("key", AppKey);
                    xElem2.SetAttribute("value", AppValue);
                    xNode.AppendChild(xElem2);
                }
                xDoc.Save(System.Windows.Forms.Application.ExecutablePath + ".config");
            }
  • 相关阅读:
    Xamarin.Android和UWP之MVVM的简单使用(二)
    Xamarin.Android和UWP之MVVM的简单使用(一)
    那些年用过的xUnit.net的简单用法
    Xamarin.Android之给我们的应用加点过渡效果
    Xamarin.Android之Splash的几种简单实现
    Xamarin.Android之布局文件智能提示问题
    Xamarin.Android之Spinner的简单探讨
    Xamarin.Android之封装个简单的网络请求类
    Xamarin.Android再体验之简单的登录Demo
    【分库分表】sharding-jdbc实践—分库分表入门
  • 原文地址:https://www.cnblogs.com/amyeeq/p/8278954.html
Copyright © 2011-2022 走看看