2016-04-15 34 views
0

我有這個代碼來從自定義.config文件中獲取所有的鍵/值,我通過它的路徑,但代碼檢索0鍵,我不明白爲什麼。代碼不會從.config文件檢索任何密鑰c#

下面的代碼:

public void UpdateService(string FilePathOld, string FilePathNew) 
{ 
    string[] Keys = { "SleepTimeInSeconds", "LogCleanInMinutes", "LogFileSize", "SqlTrans", "RemoteType", "DebugMode", "SleepError", "LogLevel", "LogSqlClient", "LogFile", "DebugRemote" }; 

    Dictionary<string, string> Old = new Dictionary<string, string>(); 
    Dictionary<string, string> New = new Dictionary<string, string>(); 

    ExeConfigurationFileMap configOld = new ExeConfigurationFileMap(); 
    configOld.ExeConfigFilename = FilePathOld; 

    Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configOld, ConfigurationUserLevel.None); 

    ExeConfigurationFileMap configNew = new ExeConfigurationFileMap(); 
    configNew.ExeConfigFilename = FilePathNew; 

    Configuration config2 = ConfigurationManager.OpenMappedExeConfiguration(configNew, ConfigurationUserLevel.None); 

    KeyValueConfigurationCollection settings = config.AppSettings.Settings; 
    Old = settings.AllKeys.ToDictionary(key => key, key => settings[key].Value); 

    KeyValueConfigurationCollection settings2 = config2.AppSettings.Settings; 
    New = settings2.AllKeys.ToDictionary(key => key, key => settings2[key].Value); 
} 
+1

的AppSettings或UserSettings或SomeOtherSettings?你正在檢查正確的節點/設置名稱?如果可能的話,請顯示配置文件。 – touchofevil

+0

我想要檢索appSettings部分中的所有設置。 這裏是配置文件:https://drive.google.com/file/d/0ByZb1KP9efohTDVhZXp1VkNBOEk/view?usp=sharing –

+0

@touchofevil在代碼中,我沒有指定我想要的部分。那可以嗎? –

回答

0

你可以從web.config中獲取鍵值到您的網頁如..

ConfigurationManager.AppSettings [ 「SleepTimeInSeconds」];

這裏「SleepTimeInSeconds」是你的鑰匙&你使用的鍵名值

你必須寫所有密鑰驗證碼...

+0

,但我需要檢索.config中的所有鍵和值到字典,如上所述。但代碼不返回任何鍵或值 –

+0

我明白,但我不能繼續這樣做,因爲我不知道文件中的所有關鍵名稱,他們甚至可能會不同。我需要返回指定任意鍵的所有鍵 –

+0

ConfigurationManager.appSettings.Keys如何從appSettings獲取所有鍵並迭代所有鍵並使用它們。 –