You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# 保存配置文件前如何将AppSettings按Key名称排序

解决方案

你原先使用的AllKeys.OrderBy(r => r)仅会返回排序后的key序列,属于LINQ的无副作用查询操作,不会修改配置集合内部的节点存储顺序,因此保存后不会生效。

正确的实现思路是先取出所有配置项按key排序,清空原有配置集合后再按排序后的顺序重新写入,完整代码如下:

Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
UpdateSetting(config, "LocalLastUpdate", remoteSettingLastUpdated);

// 排序核心逻辑
var sortedSettings = config.AppSettings.Settings.AllKeys
    .OrderBy(key => key)
    .Select(key => new { Key = key, Value = config.AppSettings.Settings[key].Value })
    .ToList();
// 清空原集合存储的配置节点
config.AppSettings.Settings.Clear();
// 按排序后的顺序重新添加配置
foreach (var setting in sortedSettings)
{
    config.AppSettings.Settings.Add(setting.Key, setting.Value);
}

config.Save(ConfigurationSaveMode.Minimal);


private static void UpdateSetting(Configuration config, string name, string value)
{
    Log.Debug("Updating Local Settings [" + name + "] -> '" + value + "'");
    config.AppSettings.Settings.Remove(name);
    config.AppSettings.Settings.Add(name, value);
}

运行后配置文件的appSettings节点会严格按照key的字母升序排列,新增的LocalLastUpdate节点会出现在最顶部,符合预期要求。

内容的提问来源于stack exchange,提问作者Sari Rahal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 06:45:04