如何在C#中读取自定义.config文件的ServerUrl键值并更新
解决读取并更新.config中AutoUpdate/Settings下ServerUrl的问题
嘿,你已经成功拿到了AutoUpdate SectionGroup,接下来只需要几步就能获取并修改ServerUrl的值了,我给你详细拆解一下:
1. 获取Settings节并转换类型
因为你的Settings节用的是System.Configuration.NameValueSectionHandler类型,所以拿到它之后需要转换成NameValueCollection来操作键值对:
var autoUpdateGroup = config.GetSectionGroup("AutoUpdate"); // 获取Settings节并转换为NameValueCollection var settingsSection = (NameValueCollection)autoUpdateGroup.Sections["Settings"];
2. 读取ServerUrl的值
现在你可以直接通过键名获取ServerUrl的值了:
string currentServerUrl = settingsSection["ServerUrl"]; // 可以打印出来验证一下 Console.WriteLine($"当前ServerUrl: {currentServerUrl}");
3. 更新ServerUrl并保存配置
修改值之后,别忘了把更改保存回.config文件,还要刷新配置让修改生效:
// 设置新的ServerUrl值 settingsSection["ServerUrl"] = "https://new-updated-url.xml"; // 保存配置更改 config.Save(ConfigurationSaveMode.Modified); // 刷新ConfigurationManager,让后续读取能拿到最新值 ConfigurationManager.RefreshSection("AutoUpdate/Settings");
完整示例代码
把这些步骤整合起来,完整的代码如下:
var configMap = new ExeConfigurationFileMap(); configMap.ExeConfigFilename = @"MyPath\My.config"; var config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None); // 获取AutoUpdate SectionGroup var autoUpdateGroup = config.GetSectionGroup("AutoUpdate"); if (autoUpdateGroup != null) { // 获取Settings节 var settingsSection = (NameValueCollection)autoUpdateGroup.Sections["Settings"]; if (settingsSection != null) { // 读取当前值 string oldUrl = settingsSection["ServerUrl"]; Console.WriteLine($"旧ServerUrl: {oldUrl}"); // 更新值 settingsSection["ServerUrl"] = "https://your-new-server-url.xml"; // 保存并刷新 config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("AutoUpdate/Settings"); // 验证更新结果 string newUrl = settingsSection["ServerUrl"]; Console.WriteLine($"新ServerUrl: {newUrl}"); } }
需要注意的是,确保你的程序有对.config文件的写入权限,不然保存的时候会抛出权限异常哦~
内容的提问来源于stack exchange,提问作者GThree
相关产品推荐
相关产品推荐

