在配置文件中定义初始值然后读取

先添加名为ConfigUtil 的类文件

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

namespace MakeSiteMap.Utils
{
    /// <summary>
    /// 对配置文件[App.config]进行操作
    /// </summary>
    public class ConfigUtil
    {
        #region Methods
        /// <summary>
        /// 通过 key 读取配置文件的值
        /// </summary>
        /// <param name="key"><add key="" value ="" /></param>
        /// <returns></returns>
        public static string Read(string key)
        {        
            return ConfigurationManager.AppSettings[key];
        }

        /// <summary>
        /// 保存修改后的配置文件
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        public static void SaveConfig(string key, string value)
        {
            Configuration cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            cfg.AppSettings.Settings[key].Value = value;
            cfg.Save(ConfigurationSaveMode.Modified);
        }

        /// <summary>
        /// 保存修改后的配置文件[XML方式]
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        public static void Save(string key, string value)
        {
            XmlDocument doc = new XmlDocument();

            string config = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;

            doc.Load(config);

            XmlNodeList nodes = doc.GetElementsByTagName("add");
            for (int i = 0; i < nodes.Count; i++)
            {
                XmlAttribute att = nodes[i].Attributes["key"];

                if (att.Value == key)
                {
                    att = nodes[i].Attributes["value"];
                    att.Value = value;
                    break;
                }
            }

            doc.Save(config);
        }
        #endregion
    }
}

=========================================================

然后再配置文件中设定初始值在</appSettings>之上

   <add key="CurrentNum" value="77818" />
  </appSettings>

然后在程序中读取CurrentNum的值value

string file = ConfigUtil.Read("CurrentNum");

再在程序一次执行完成后修改配置文件中CurrentNum

file = ds.Tables[0].Rows[ds.Tables[0].Rows.Count - 1]["商家编码"].ToString();  //修改
                ConfigUtil.SaveConfig("CurrentNum", file);   //保存修改

你可能感兴趣的:(配置文件)