Newer
Older
RbFreqStand / RbFreqStandMeasure / tools / ConfigHelper.cs
yangqianqian on 8 May 2021 2 KB s
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Reflection;

namespace Casic.Birmm.RbFreqStandMeasure.Tools
{
    class ConfigHelper
    {
        public static string GetAppConfig(string strKey)
        {
            string file = System.Windows.Forms.Application.ExecutablePath;
            Configuration config = ConfigurationManager.OpenExeConfiguration(file);
            foreach (string key in config.AppSettings.Settings.AllKeys)
            {
                if (key == strKey)
                {
                    return config.AppSettings.Settings[strKey].Value.ToString();
                }
            }
            return null;
        }

        public static string getKeyByValue(string value)
        {
            try
            {
                string file = System.Windows.Forms.Application.ExecutablePath;
                Configuration config = ConfigurationManager.OpenExeConfiguration(file);
                foreach (string key in config.AppSettings.Settings.AllKeys)
                {
                    string val = config.AppSettings.Settings[key].Value.ToString();
                    if (val.Equals(value))
                    {
                        return key;
                    }
                }
            }
            catch (Exception e)
            {
                LogHelper.WriteErrorLog(MethodBase.GetCurrentMethod().DeclaringType, "getKeyByValue:" + e.Message);

            }
            return null;
        }
            

        public static void UpdateAppConfig(string newKey, string newValue)
        {
            string file = System.Windows.Forms.Application.ExecutablePath;
            Configuration config = ConfigurationManager.OpenExeConfiguration(file);
            bool exist = false;
            foreach (string key in config.AppSettings.Settings.AllKeys)
            {
                if (key == newKey)
                {
                    exist = true;
                }
            }

            if (exist)
            {
                config.AppSettings.Settings.Remove(newKey);
            }
            config.AppSettings.Settings.Add(newKey, newValue);
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }
    }
}