1. 程式人生 > >配置檔案操作類(.AppConfig)

配置檔案操作類(.AppConfig)

class SetConfig
    {
        //獲取AppConfig
        public static string GetAppConfig(string strKey)
        {
            foreach (string key in ConfigurationManager.AppSettings)
            {
                if (key == strKey)
                {
                    return ConfigurationManager.AppSettings[strKey];
                }
            }
            return null;
        }


        //更新配置節
        public static void UpdateAppConfig(string newKey, string newValue)
        {
            bool isModified = false;// 記錄該Key是否已經存在
            // 如果要更改的Key已經存在
            foreach (string key in ConfigurationManager.AppSettings)
            {
                if (key == newKey)
                {
                    isModified = true;
                }
            }
            //開啟 App.Config
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            // 如果連線串已存在,首先刪除它
            if (isModified)
            {
                config.AppSettings.Settings.Remove(newKey);
            }
            //新增新的配置到配置檔案裡
            config.AppSettings.Settings.Add(newKey, newValue);
            //儲存對配置節所做的更改
            config.Save(ConfigurationSaveMode.Modified);
            //強制過載配置節
            ConfigurationManager.RefreshSection("appSettings");
        }
    }