您的位置:首页 > 理论基础 > 计算机网络

如何用C#读写配置文件(转载自网络)

2016-09-21 09:47 363 查看
读配置很简单,可以用ConfigurationManager.AppSettings[key] 来读出,

可是写配置文件时,如果写成这样

ConfigurationManager.AppSettings[key] = "111";

总是提示只读,那么该怎么办呢?

 

using System;  

using System.Collections.Generic;  

using System.Text;  

using System.Configuration;  

  

namespace BQKJ.Common  

{  

    /// <summary>   

    /// 对exe.Config文件中的appSettings段进行读写配置操作   

    /// 注意:调试时,写操作将写在vhost.exe.config文件中   

    /// </summary>   

    public class ConfigAppSettings  

    {  

        /// <summary>   

        /// 写入值   

        /// </summary>   

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

        /// <param name="value"></param>   

        public static void SetValue(string key, string value)  

        {  

            //增加的内容写在appSettings段下 <add key="RegCode" value="0"/>   

            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);  

            if (config.AppSettings.Settings[key] == null)  

            {  

                config.AppSettings.Settings.Add(key, value);  

            }  

            else  

            {  

                config.AppSettings.Settings[key].Value = value;  

            }  

            config.Save(ConfigurationSaveMode.Modified);  

            ConfigurationManager.RefreshSection("appSettings");//重新加载新的配置文件    

        }  

  

        /// <summary>   

        /// 读取指定key的值   

        /// </summary>   

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

        /// <returns></returns>   

        public static string GetValue(string key)  

        {   

            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);  

            if (config.AppSettings.Settings[key] == null)  

                return "";  

            else  

                return config.AppSettings.Settings[key].Value;  

        }  

  

    }  

}  

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: