C# 操做配置文件的方法

using System; using System.Configuration; namespace HT.IMS.Utility { /// <summary>
    /// 操做配置文件(修改) /// </summary>
    public class AppSettings { /// <summary>
        /// 設置配置文件AppSettings節點的鍵名和值並持久化到文件 /// </summary>
        /// <param name="key">節點名稱</param>
        /// <param name="value">節點值</param>
        public static void SetConfig(string key, string value) { try { //打開配置文件流
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); AppSettingsSection section = config.AppSettings; if (section != null && section.Settings[key] != null) { section.Settings[key].Value = value; } else { section.Settings.Add(new KeyValueConfigurationElement(key, value)); } //保存修改後的節點
 config.Save(ConfigurationSaveMode.Modified); //刷新節點,以便下次從 ConfigurationManager.AppSettings 中取值時, //從新從磁盤讀取節點的值
                ConfigurationManager.RefreshSection("appSettings"); } catch (Exception ex) { throw ex; } } public static void SetConfigConnectionstring(string key, string value) { try { Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); ConnectionStringsSection section = config.ConnectionStrings; if (section != null && section.ConnectionStrings[key] != null) { section.ConnectionStrings[key].ConnectionString = value; } else { section.ConnectionStrings.Add(new ConnectionStringSettings(key, value, "System.Data.SqlClient")); } config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("connectionStrings"); } catch (Exception ex) { throw ex; } } } /// <summary>
    /// 操做配置文件(讀取) /// </summary>
    /// <typeparam name="T">返回什麼類型的值</typeparam>
    public class AppSettings<T> : AppSettings { public static T GetConfig(string key, byte valType = 0) { try { Type type = typeof(T); object result = null; //返回特定類型的值 
                object val = null; //配置節點的值

                if (valType == 0) val = ConfigurationManager.AppSettings[key]; else val = ConfigurationManager.ConnectionStrings[key]; if (type == typeof(int)) result = Convert.ToInt32(val); else if (type == typeof(string)) result = Convert.ToString(val); else if (type == typeof(double)) result = Convert.ToDouble(val); else result = Convert.ChangeType(val, type); return (T)result; } catch { return default(T); } } } }
相關文章
相關標籤/搜索