使用代码修改配置文件的方法:
1、打开配置文件写入的权限
2、先按节点名称长到要修改的节点,然后删除,紧接着将有新值的节点添加回去
3、关闭配置文件写入的权限
修改Appsetting节点的值,修改其它节点的方法也差不多,也是找到要修改的节点删除掉然后新新值的节点加上
public bool UpdateAppSettings(string key, string value) { bool reuslt = false; try { Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); SetFileAccess(config.FilePath + "", false); ConfigurationSection sections = config.GetSection("appSettings"); bool isSet = false; for (int i = 0; i < ((System.Configuration.AppSettingsSection)(sections)).Settings.Count; i++) { string itemkey = ((System.Configuration.AppSettingsSection)(sections)).Settings.AllKeys[i]; if (itemkey == key) { ((System.Configuration.AppSettingsSection)(sections)).Settings.Remove(key); ((System.Configuration.AppSettingsSection)(sections)).Settings.Add(key, value); isSet = true; break; } } if (!isSet) { ((System.Configuration.AppSettingsSection)(sections)).Settings.Add(key, value); } config.Save(); ConfigurationManager.RefreshSection("appSettings"); SetFileAccess(config.FilePath + "", true); reuslt = true; } catch (Exception ex) { LogNet.Log.WriteLog("UpdateAppSettings", ex); } return reuslt; }
修改配置文件的读写权限
protected void SetFileAccess(string path, bool isReadOnly) { FileInfo fi = new FileInfo(path); if (fi.IsReadOnly != isReadOnly) fi.IsReadOnly = isReadOnly; }
时间: 2024-11-09 06:23:36