在运行时修改app.config会引发异常 [英] Modifying app.config at runtime throws exception
问题描述
我正在使用app.config
文件存储和读取一些参数(SQL Server实例名称,用户,密码,日志目录等).现在,仅当我从bin/release目录运行.exe
时,我才需要修改一些取决于用户的参数并对此进行管理.
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.
当我创建安装程序并安装我的应用程序时,我无法更改此参数-它抛出TargetInvocationException
.我试图以管理员身份运行我的应用程序,但没有成功.
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");
我尝试了在stackoverflow上找到的其他一些解决方案,但没有成功.
I've tried a few other solutions found on stackoverflow but without success.
推荐答案
理想情况下,我们无法在应用程序运行时修改配置项.
Ideally we cannot modify config entries when application is running.
从bin中运行exe时,它没有修改* .exe.config.
When you ran the exe from bin, it didn't modify the *.exe.config .
相反,它修改了 *.vshost.exe.Config 文件.
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); returns reference to *.vshost.exe.Config file
*.exe.config是只读的,您无法更新此文件.
*.exe.config is read only, you cannot update this file.
这篇关于在运行时修改app.config会引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!