通过传递 .config 文件的路径将 key/value 对读取到字典中 c#

Reading a key/value pair to a dictionary by passing the path of the .config file c#

我有两个配置文件,旧版本和最新版本。 我需要更新旧的,所以我编写了以下代码来打开两者并将 key/value 加载到我稍后将比较的两个词典中。 代码如下: 需要更改什么?

 public void UpdateCliente(string FilePathOld, string FilePathNew)
 {
      Dictionary<string, string> Old = new Dictionary<string, string>();
      Dictionary<string, string> New = new Dictionary<string, string>();
      List<string> KeysOld = new List<string>();
      List<string> KeysNew = new List<string>();
      //Keys = ConfigurationSettings.AppSettings.AllKeys.ToList();

      ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
      configMap.ExeConfigFilename = FilePathOld;
      Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
       KeysOld = config.AppSettings.Settings.AllKeys.ToList();

       Old = (config.GetSection("<appSettings>") as System.Collections.Hashtable)
                .Cast<System.Collections.DictionaryEntry>()
                .ToDictionary(n => n.Key.ToString(), n => n.Value.ToString());

      //Old = (config.GetSection("<appSettings>") as System.Collections.Hashtable)

  }

这一行:Old = (config.GetSection("<appSettings>") as System.Collections.Hashtable) 给我以下错误:

Cannot convert type 'System.Configuration.ConfigurationSection' to 'System.Collections.Hashtable' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion

NOTE: I forgot the code to convert the keys of the newer file but the method should be the same!

你是说,例如...

Configuration config = 
    ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

KeyValueConfigurationCollection settings = 
    config.AppSettings.Settings;

Dictionary<string, string> dictionary = 
    settings.AllKeys.ToDictionary(key => key, key => settings[key].Value);

还有,我觉得应该是config.GetSection("appSettings")

您使用了错误的类型。

Configuration.GetSection() returns 不是 Hashtable.

ConfigurationSection 对象

下面的代码应该可以解决问题:

var appSettings = config.GetSection("appSettings") as AppSettingsSection;
foreach(var key in appSettings.Settings.AllKeys)
{
    Old[key] = appSettings.Settings[key].Value;
}