2011-09-01 31 views
1

我有一個exe文件,從本地app.config文件中讀取一些值來更新值:在當地的app.config

TargetDate = ConfigurationManager.AppSettings.Get("ThresholdDate"); 

// and try to update with the current date 
ConfigurationManager.AppSettings.Set("ThresholdDate", "2011-09-01"); 

我想它的工作一次,但我沒有看到app.config以獲取更新所有現在。

+1

這是有幫助:http://stackoverflow.com/questions/980440/update-app-config-system-net-setting-at-runtime – Baz1nga

回答

2

我想你可以嘗試這樣的事:

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None) 
//change the config value 
config.Save(ConfigurationSaveMode.Modified); 
ConfigurationManager.RefreshSection("appSettings"); 

我不知道生根粉語法改變的配置價值,但我以前做過一個Add,我知道你可以做一個刪除,所以我想你可以做刪除的組合,並添加這樣的:

config.AppSettings.Settings.Remove("ThresholdDate"); 
config.AppSettings.Settings.Add("ThresholdDate", "2011-09-01"); 
+0

什麼是改變配置值的C#語法? – user360943

+0

嘗試刪除和添加...嗯沒有改變一件事 – user360943

+0

你做了保存和刷新後? – Baz1nga

2

尋找這裏:How to change App.config file run time using C#就是答案 - 而在Visual Studio IDE中運行,你將不會看到值堅持在/bin/appname.exe的.config。你實際上必須進入bin目錄並運行exe。

所以這個代碼實際工作,只是沒有在調試模式:

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

config.AppSettings.Settings["ThresholdDate"].Value = Convert.ToString(testdate); 
config.Save(ConfigurationSaveMode.Modified); 
ConfigurationManager.RefreshSection("appSettings"); 
+2

如果它解決了您的問題,您應該將其標記爲您接受的答案(48小時計時器應該現在過期) – Matthieu

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

config.AppSettings.Settings["ThresholdDate"].Value = Convert.ToString(testdate); 
config.Save(ConfigurationSaveMode.Modified); 
ConfigurationManager.RefreshSection("appSettings"); 

這隻會工作,而你不是在調試運行模式。嘗試在/debug/appName.exe中運行yung代碼,然後您將在appName.exe.config中進行更改

乾杯!