C# 读取,删除,增加,修改app.config配置文件信息

2020-01-07 更新
20180509更新,新增 --添加,修改,删除功能

以下是  app.config文件里面代码

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="lqwvje" value="罗分明"/>
  </appSettings>
</configuration>


以下是读取配置文件信息方法 引用程序集System.Configuration

        /// <summary>
        /// 修改和添加AppSettings中配置 如果相应的Key存在则修改 如不存在则添加
        /// </summary>
        /// <param name="key">key值</param>
        /// <param name="value">相应值</param>
        public static bool SetConfigValue(string key, string value)
        {//转载请保留 http://www.luofenming.com/show.aspx?id=ART2018030100002
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                if (config.AppSettings.Settings[key] != null)
                {
                    config.AppSettings.Settings[key].Value = value;
                }
                else
                {
                    config.AppSettings.Settings.Add(key, value);
                }

                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="keyName"></param>
        public static void removeItem(string keyName)
        {
            //删除配置文件键为keyName的项  
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.AppSettings.Settings.Remove(keyName);
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }

        /// <summary>
        /// 查看相应Key的Value
        /// </summary>
        /// <param name="keyName"></param>
        /// <returns></returns>
        public static string valueItem(string keyName)
        {
            //返回配置文件中键为keyName的项的值  
            return ConfigurationManager.AppSettings[keyName];
        }

注意:修改和删除不是在APP.Config里面修改,改是复制在另外一个文件里面如下图


评论