Modifying app.config at runtime throws exception

别说谁变了你拦得住时间么 提交于 2020-01-16 18:11:28

问题


I'm using app.config file to store and read some parameters (sql server instance name, user, password, log directory, etc). Now, I need to modify some parameters which depends of user and managed this but only if I run .exe from bin/release directory.

When I create setup and install my aplication I'm not able to change this parameters - it throws TargetInvocationException. I've tried to run my app as administrator but without success.

The code which I currently use is the following:

System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Remove("username");
config.AppSettings.Settings.Add("username", this.Config.Username);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");

I've tried a few other solutions found on stackoverflow but without success.


回答1:


Ideally we cannot modify config entries when application is running.

When you ran the exe from bin, it didn't modify the *.exe.config .

instead it modified *.vshost.exe.Config file.

System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); returns reference to *.vshost.exe.Config  file

*.exe.config is read only, you cannot update this file.




回答2:


Try something like this

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
KeyValueConfigurationCollection settings = config.AppSettings.Settings;
 // update SaveBeforeExit
 settings[username].Value = "newkeyvalue"; //how are you getting this.Config.Username
  ...
 //save the file
 config.Save(ConfigurationSaveMode.Modified);
 //relaod the section you modified
 ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name);

Here are some Steps to Follow For example if I wanted to modify a setting based on DateTime value.. this simple explanation should make it easy for you to follow.

 1: // Open App.Config of executable   
 2: System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);   
 3: // Add an Application Setting.   
 4: config.AppSettings.Settings.Remove("LastDateChecked");   
 5: config.AppSettings.Settings.Add("LastDateChecked", DateTime.Now.ToShortDateString());   
 6: // Save the configuration file.   
 7: config.Save(ConfigurationSaveMode.Modified);   
 8: // Force a reload of a changed section.   
 9: ConfigurationManager.RefreshSection("appSettings");


来源:https://stackoverflow.com/questions/8807218/modifying-app-config-at-runtime-throws-exception

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!