2013-05-30 34 views
2

有人可以幫助我理解爲什麼在向配置文件添加值後,我無法立即將它讀入應用程序中?我會刷新,但這不起作用。見下:無法讀取appSettings直到重新啓動應用程序

public void AddConfig(string key_value, string actual_value) 
    { 
     // Open App.Config of executable 
     System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath); 
     //If it exists, remove it first 
     config.AppSettings.Settings.Remove(key_value); 
     // Add an Application Setting. 
     config.AppSettings.Settings.Add(key_value, actual_value);    
     // Save the configuration file. 
     config.Save(ConfigurationSaveMode.Modified); 
     // Force a reload of a changed section.    
     ConfigurationManager.RefreshSection("appSettings"); 
     string blah = ConfigurationManager.AppSettings[key_value]; 
     MessageBox.Show(blah); 
    } 

消息框將顯示爲空/空白。

如果我重新啓動應用程序並運行其他命令以在啓動後讀取鍵值,它將起作用。

任何想法?

回答

1

由於在Visual Studio環境中運行應用程序,您所遇到的很可能是由於該應用程序。

直接從DebugRelease目錄運行.exe並且RefreshSection()方法將按預期工作。

如果你想看到改變的值在調試時,你需要使用AppSettings.Settings而不是ConfigurationManager.AppSettings

string blah = config.AppSettings.Settings[key_value].Value 
+0

這是它....當我從調試運行,這是行不通的。當我運行實際的應用程序時,它的工作。 – user2437909

相關問題