1.新建app.config文件

项目文件右键-添加-新建项-在弹出窗口中选择应用程序配置文件
在这里插入图片描述
在这里插入图片描述
2.添加读取app.config XML文件类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Xml;

namespace TestDatabaseApplication
{
    /// <summary>
    /// 配置文件类型,是WinForm还是WebForm
    /// </summary>
    public enum ConfigFileType
    {
        WebConfig,
        AppConfig
    }
    /// <summary>
    /// 对AppSettings节点进行增加,删除,修改操作.
    /// </summary>
    class AppSettingsHelper
    {
        public static string docName = String.Empty;
        private static XmlNode node = null;


        /// <summary>
        /// 设置节点的值,若该节点不存在,则创建一个新的节点。
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="cfgType"></param>
        /// <returns></returns>
        public static bool SetValue(string key, string value, ConfigFileType cfgType)
        {
            XmlDocument cfgDoc = new XmlDocument();
            loadConfigDoc(cfgDoc, cfgType);
            // retrieve the appSettings node   
            node = cfgDoc.SelectSingleNode("//appSettings");
            if (node == null)
            {
                throw new InvalidOperationException("appSettings section not found");
            }
            try
            {
                // XPath select setting "add" element that contains this key       
                XmlElement addElem = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");
                if (addElem != null)
                {
                    addElem.SetAttribute("value", value);
                }
                // not found, so we need to add the element, key and value   
                else
                {
                    XmlElement entry = cfgDoc.CreateElement("add");
                    entry.SetAttribute("key", key);
                    entry.SetAttribute("value", value);
                    node.AppendChild(entry);
                }
                //save it   
                saveConfigDoc(cfgDoc, docName);
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 获取节点的值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="cfgType"></param>
        /// <returns></returns>
        public static string GetValue(string key, ConfigFileType cfgType)
        {
            XmlDocument cfgDoc = new XmlDocument();
            loadConfigDoc(cfgDoc, cfgType);
            // retrieve the appSettings node   
            node = cfgDoc.SelectSingleNode("//appSettings");
            if (node == null)
            {
                throw new InvalidOperationException("appSettings section not found");
            }

            // XPath select setting "add" element that contains this key       
            XmlElement addElem = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");
            if (addElem != null)
            {

                return addElem.GetAttribute("value");
            }
            // not found, so we need to add the element, key and value   
            else
            {
                throw new ArgumentException(string.Format("key '{0}' not found", key));
            }


        }


        private static void saveConfigDoc(XmlDocument cfgDoc, string cfgDocPath)
        {
            try
            {
                XmlTextWriter writer = new XmlTextWriter(cfgDocPath, null);
                writer.Formatting = Formatting.Indented;
                cfgDoc.WriteTo(writer);
                writer.Flush();
                writer.Close();
                return;
            }
            catch
            {
                throw;
            }
        }



        /// <summary>
        /// 移除节点
        /// </summary>
        /// <param name="elementKey"></param>
        /// <param name="cfgType"></param>
        /// <returns></returns>
        public static bool RemoveElement(string elementKey, ConfigFileType cfgType)
        {
            try
            {
                XmlDocument cfgDoc = new XmlDocument();
                loadConfigDoc(cfgDoc, cfgType);
                // retrieve the appSettings node  
                node = cfgDoc.SelectSingleNode("//appSettings");
                if (node == null)
                {
                    throw new InvalidOperationException("appSettings section not found");
                }
                // XPath select setting "add" element that contains this key to remove      
                node.RemoveChild(node.SelectSingleNode("//add[@key='" + elementKey + "']"));
                saveConfigDoc(cfgDoc, docName);
                return true;
            }
            catch
            {
                return false;
            }
        }


        /// <summary>
        /// 修改节点的值
        /// </summary>
        /// <param name="elementKey"></param>
        /// <param name="cfgType"></param>
        /// <returns></returns>
        public static bool ModifyElement(string elementKey, ConfigFileType cfgType)
        {
            try
            {
                XmlDocument cfgDoc = new XmlDocument();
                loadConfigDoc(cfgDoc, cfgType);
                // retrieve the appSettings node  
                node = cfgDoc.SelectSingleNode("//appSettings");
                if (node == null)
                {
                    throw new InvalidOperationException("appSettings section not found");
                }
                // XPath select setting "add" element that contains this key to remove      
                node.RemoveChild(node.SelectSingleNode("//add[@key='" + elementKey + "']"));
                saveConfigDoc(cfgDoc, docName);
                return true;
            }
            catch
            {
                return false;
            }
        }



        private static XmlDocument loadConfigDoc(XmlDocument cfgDoc, ConfigFileType cfgType)
        {
            // load the config file   
            if (cfgType == ConfigFileType.AppConfig)
            {
                docName = ((Assembly.GetEntryAssembly()).GetName()).Name;
                docName += ".exe.config";
            }
            else
            {
                //docName = HttpContext.Current.Server.MapPath("web.config");
            }
            cfgDoc.Load(docName);
            return cfgDoc;
        }

    }

}

3.对文件进行读写操作

在app.config文件中添加值

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="test1" value="I am test1" ></add>
  </appSettings>
</configuration>

在程序中读取值

 private void button1_Click(object sender, EventArgs e)
        {
            string sTest = AppSettingsHelper.GetValue("test1", ConfigFileType.AppConfig);
            Console.WriteLine("sTest=" + sTest);
        }

4.写入值

 private void button2_Click(object sender, EventArgs e)
        {
            AppSettingsHelper.SetValue("test332", "i am test32", ConfigFileType.AppConfig);
        }

在bin\debug下的TestDatabaseApplication.exe.Config可以查看到写入的值
在这里插入图片描述
在这里插入图片描述

4.题外话

有一点值得注意的是app.config写入的值其实是在项目目录\bin\Debug\项目文件名.exe.Config文件里的。

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐