在程式裡修改app.config的值

  • 4976
  • 0

一般.NET程式會把設定存放在app.config,有時候想要在程式裡修改設定,我知道網路上有一些用XmlDoc修改的做法,但我覺得還是用.NET提供的方法比較好.這文章是我很久之前寫的了,把它從wordpress轉過來以免要找的時候找不到.

修改app.config跟修改web.config是很相似的,修改web.confg的文章可以看這一篇

下面的程式碼片段會打開app.config,再透過Configuration object去修改設定值,然後把修改儲存.

在你執行程式並用程式修改設定檔後,你會發現你的app.config並沒有改變.

這是因為被修改的.config是放在\bin\Debug或\bin\Release裡的實際編譯完的application.exe.config.

Configuration l_appConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
AppSettingsSection appSettings = (AppSettingsSection)l_appConfig.GetSection("appSettings");
//let say you want to modify the setting name DatabaseHost
appSettings.Settings["DatabaseHost"].Value = "blahblahblah";
l_appConfig.Save();
ConfigurationManager.RefreshSection("appSettings");

 

My WP Blog with english technical docs.