首页 > 解决方案 > 从 C# 中的配置文件读取保持顺序的键值对

问题描述

我将配置存储在 app.config 文件中,如下所示:

<configSections>
    <sectionGroup name="FieldMappingSettings">
      <section name="RequiredFields" type="System.Configuration.DictionarySectionHandler"/>
    </sectionGroup>
  </configSections>

  <FieldMappingSettings>
    <RequiredFields>
      <add key="ColumnName 1" value="Config Value1" />
      <add key="ColumnName 2" value="Config Value2" />
      <add key="ColumnName 3" value="Config Value3" />
      <add key="ColumnName 4" value="Config Value4" />
      <add key="ColumnName 5" value="Config Value5" />
    </RequiredFields>
  </FieldMappingSettings>

我正在阅读这些键值对使用

var requiredFields = (ConfigurationManager.GetSection("FieldMappingSettings/RequiredFields") as System.Collections.Hashtable)
             .Cast<System.Collections.DictionaryEntry>()
             .ToDictionary(n => n.Key.ToString(), n => n.Value.ToString());

我需要以相同的顺序使用此配置进行进一步处理,但与System.Collections.Hashtable用于强制转换一样,这些键值不按配置顺序存储(Hashtable使用散列键存储它们)。

所以问题是:

既然返回类型ConfigurationManager.GetSection()object,我们可以把它转换成Dictionary<string, string>代替Hashtable吗?

或者

有没有其他方法可以读取键值对来维护它们的配置顺序?

标签: c#type-conversionhashtableapp-config

解决方案


推荐阅读