2016-04-13 28 views
0

我有兩個配置文件,即舊版本和最新版本。 我需要更新舊的,所以我做了下面的代碼來打開兩個並將鍵/值加載到兩個字典中,稍後我會進行比較。 代碼如下: 需要更改哪些內容?通過傳遞.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)使我有以下錯誤:

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!

回答

4

你的意思是,例如...

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")

+0

只是一個小問題。這段代碼將返回文件中的所有密鑰?我只是在「appSettings」部分中的鍵 –

+0

返回所有在appSettings –

+0

好吧,謝謝,實際上這並不重要,因爲我必須檢查我可以和不能改變的鍵 –

1

您正在使用錯誤的類型。

Configuration.GetSection()返回一個ConfigurationSection對象,它不是Hashtable

下面的代碼應該做的伎倆:

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