读取、添加、删除、修改配置文件 如(Web.config, App.config)
1 private Configuration config; 2 public OperateConfig() 3 : this(HttpContext.Current.Request.ApplicationPath) 4 { 5 } 6 7 public OperateConfig(string path) 8 { 9 config = WebConfigurationManager.OpenWebConfiguration(path); 10 } 11 12 /// <summary> 13 /// 设置应用程序配置节点,如果已经存在此节点,则会修改该节点的值,否则添加此节点 14 /// </summary> 15 /// <param name="key"></param> 16 /// <param name="value"></param> 17 public void SetAppSetting(string key, string value) 18 { 19 AppSettingsSection appSetting = (AppSettingsSection)config.GetSection("appSettings"); 20 if (appSetting.Settings[key] == null) 21 { 22 appSetting.Settings.Add(key, value); 23 } 24 else 25 { 26 appSetting.Settings[key].Value = value; 27 } 28 } 29 30 /// <summary> 31 /// 设置数据库连接字符串节点,如果不存在此节点,则会添加此节点及对应的值,存在则修改 32 /// </summary> 33 /// <param name="key"></param> 34 /// <param name="connectionString"></param> 35 public void SetConnectionString(string key, string connectionString) 36 { 37 ConnectionStringsSection connectionSetting = (ConnectionStringsSection)config.GetSection("connectionStrings"); 38 if (connectionSetting.ConnectionStrings[key] == null)//如果不存在此节点,则添加 39 { 40 ConnectionStringSettings connectionStringSettings = new ConnectionStringSettings(key, connectionString); 41 connectionSetting.ConnectionStrings.Add(connectionStringSettings); 42 } 43 else//如果存在此节点,则修改 44 { 45 connectionSetting.ConnectionStrings[key].ConnectionString = connectionString; 46 } 47 } 48 49 /// <summary> 50 /// 保存所作的修改 51 /// </summary> 52 public void Save() 53 { 54 config.Save(); 55 config = null; 56 } 57 58 public void Dispose() 59 { 60 if (config != null) 61 { 62 config.Save(); 63 } 64 }