无法动态更改app.config值 [英] Unable to chage app.config value dynamically
问题描述
我正在使用Visual Studio,搜索后发现以下代码可以动态修改app.config文件
I am using Visual Studio, after searching i''ve found this following code to modify app.config file dynamically
Configuration configFile = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
configFile.AppSettings.Settings["Servername"].Value = "Server-PC";
configFile.Save();
但是在pmy项目中应用此方法时,出现以下错误
But while applying this in pmy project i am getting this following error
错误35找不到类型或名称空间名称"Configuration"(您是否缺少using指令或程序集引用? )
Error 35 The type or namespace name ''Configuration'' could not be found (are you missing a using directive or an assembly reference?)
和
错误36名称"ConfigurationManager"在当前上下文中不存在
Error 36 The name ''ConfigurationManager'' does not exist in the current context
有人可以建议我如何动态更改app.config值吗?
Can anyone please suggest me how to change app.config value dynamically?
推荐答案
在
System.Configuration
中添加引用您的项目.
如果添加了此引用,则在页面上的名称空间下方添加
in your project.
if you added this reference then add below namespace on your page
using System.Configuration;
最后,我得到了解决方案
选中此链接 [ ^ ]
Finally i''ve got the solution
check this link[^]
// Open App.Config of executable
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// Add an Application Setting.
config.AppSettings.Settings.Remove("connection");
config.AppSettings.Settings.Add("connection", server);
// Save the configuration file.
config.Save(ConfigurationSaveMode.Modified);
// Force a reload of a changed section.
ConfigurationManager.RefreshSection("appSettings");
这篇关于无法动态更改app.config值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!