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



我有两个配置文件,旧版本和最新版本。我需要更新旧的,所以我制作了以下代码来打开这两个字典,并将键/值加载到两个字典中,稍后将进行比较。代码如下:需要改变什么?

 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)给我以下错误:

无法将类型"System.Configuration.ConfigurationSection"转换为"System.Collections.Hashtable"通过引用转换,装箱转换、取消装箱转换、包装转换或null类型转换

注意:我忘记了转换新文件密钥的代码,但方法应该相同!

你的意思是,例如。。。

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()返回一个不是HashtableConfigurationSection对象。

下面的代码应该可以做到这一点:

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

最新更新