2012-01-10 62 views
0

我使用app.config文件来存储和读取一些参数(sql服务器实例名称,用户,密码,日志目录等)。现在,我需要修改一些依赖于用户的参数,并且只有在我从bin/release目录运行.exe时才管理它。 当我创建安装程序并安装我的应用程序时,我无法更改此参数 - 它会引发TargetInvocationException。我试图以管理员身份运行我的应用程序,但没有成功。在运行时修改app.config抛出异常

的代码,我目前使用的是以下几点:

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"); 

我试过计算器上,但没有成功发现了一些其他的解决方案......

+0

当你运行代码,你有什么值this.Config.Username .. ?? – MethodMan 2012-01-10 17:11:40

+1

这是一个非常经典的UAC陷阱。您可以在开发机器上调试程序时修改该文件,但安装后无法运行。 'c:\ program files'中的文件是不可写的。您需要一个单独的程序来编辑该文件,以便它可以请求UAC提升。或者不使用设置来存储这些信息,AppData中的.xml文件也可以工作。 – 2012-01-10 18:42:02

+0

用户名@DJKRAZE的值是有效的。阅读作品。 – davor 2012-01-10 20:24:07

回答

0

尝试是这样的

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); 

这里有一些步骤要遵循例如,如果我想修改一个基于日期时间值的设置..这个简单的解释应该可以让您轻松遵循。

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"); 
0

理想情况下,我们无法在应用程序运行时修改配置条目。

当您从bin运行exe时,它不会修改* .exe.config。

改为修改* .vshost.exe.Config文件。

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

* .exe.config是只读的,您无法更新此文件。