[英]Modifying app.config at runtime throws exception
我正在使用app.config
文件存储和读取一些参数(SQL Server实例名称,用户,密码,日志目录等)。 现在,仅当我从bin / release目录运行.exe
,我才需要修改一些取决于用户的参数并对此进行管理。
创建安装程序并安装应用程序时,我无法更改此参数-它会引发TargetInvocationException
。 我试图以管理员身份运行我的应用程序,但没有成功。
我当前使用的代码如下:
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");
我尝试了在stackoverflow上找到的其他一些解决方案,但没有成功。
试试这个
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);
以下是一些要遵循的步骤,例如,如果我想基于DateTime值修改设置。.这个简单的说明应该使您易于遵循。
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");
理想情况下,我们无法在应用程序运行时修改配置条目。
从bin运行exe时,它没有修改* .exe.config。
相反,它修改了* .vshost.exe.Config文件。
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); returns reference to *.vshost.exe.Config file
* .exe.config是只读的,您无法更新此文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.