App.config和配置文件的读写

主要用来读取数据库连接,当然也可以设置其他项,废话不多说看代码

using System;

using System.Collections.Generic;

using System.Text;

using System.Configuration;

using System.Collections;

using System.Xml;

using System.Windows.Forms;

 

namespace Windo

{

    class AppClass1

    {

        // GetConfiguration#region GetConfiguration

        /**/

        /// <summary>

        /// 取得appSettings里的值

        /// </summary>

        /// <param name="key">键</param>

        /// <returns>值</returns>

        public static string GetConfiguration(string key)

        {

            return ConfigurationSettings.AppSettings[key];

        }

        public static string  GetConfigValue()

        {

            string conn;

            XmlDocument xDoc = new XmlDocument();

            try

            {

                //加载app.config文件

                //xDoc.Load(Application.ExecutablePath + ".config");  //这个读取的是:项目名.exe.config文件

                xDoc.Load("D:\\Demo\\Windo\\Windo\\Windo\\app.config");  //这里是读取app.config文件

                //寻找add元素

                XmlElement xElem1 = (XmlElement)xDoc.SelectSingleNode("/configuration/connectionStrings/add");

                if (xElem1 != null)

                {

                    //返回add元素中connectionString属性值

                    conn = xElem1.GetAttribute("connectionString");

                   // MessageBox.Show(xElem1.GetAttribute("connectionString"));

                    return conn;

                }

                return conn = "读取错误!";

            }

            catch (Exception)

            {

                conn = "读取错误!";

                return conn;

            }

        }

       

        public static string GetConfigString(string key)

        {

            // TODO: 在此处添加构造函数逻辑

            return ConfigurationSettings.AppSettings[key];

        }

        //写操作

        public void SetValue(string AppKey, string AppValue)

        {

            XmlDocument xDoc = new XmlDocument();

            //获取可执行文件的路径和名称

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

 

            XmlNode xNode;

            XmlElement xElem1;

            XmlElement xElem2;

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

 

            xElem1 = (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");

        }

    }

 

/// <summary>

/// 没啥用,狗头军师老出错。

/// </summary>

    public class AppConfig

    {

        private XmlDocument Doc = new XmlDocument();

        private AppDomain Ad = AppDomain.CurrentDomain;

        public AppConfig()

        {

            Doc.Load(Ad.SetupInformation.ConfigurationFile);

        }

        public void LoadAppConfig()

        {

            Doc.Load(Ad.SetupInformation.ConfigurationFile);

        }

        public void SetAppValue(string key, string newValue)

        {

            Doc.SelectSingleNode("/configuration/appSettings/add[@key='" + key + "']").Attributes["value"].Value = newValue;

        }

        public void SaveAppConfig()

        {

            Doc.Save(Ad.SetupInformation.ConfigurationFile);

            Doc.Load(Ad.SetupInformation.ConfigurationFile);

        }

        public string GetAppValue(string key)

        {

            return Doc.SelectSingleNode("/configuration/appSettings/add[@key='" + key + "']").Attributes["value"].Value;

            //return Doc.SelectSingleNode("/configuration/connectionStrings/add[@key='" + key + "']").Attributes["value"].Value;

        }

    }

}

 

在开发Web项目的时候,会有一个配置文件Web.config,用来存放一些全局的变量,如连接数据库用的字符串。相应的,在开发winform 程序时,也有一个配置文件,它就是App.config,这个文件的作用与Web.config大致相同,也可以用来存放程序所用的全局变量及Value 值。

来看一个app.config文件的例子:
<?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值。

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


        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");
        }

        注意这个方法中if条件else下的语句,当在文件中没有找到给定的元素时,方法会创建这个元素。

posted on 2012-05-03 15:48  Arrow.Lu  阅读(206)  评论(0)    收藏  举报