在WPF程序运行时动态修改app.config文件后如何立即生效 10
我需要在程序运行时动态的修改app.config文件,立即生效不用重启程序。现在用ConfigurationManager可以在app.config中写入新的值,但是必须...
我需要在程序运行时动态的修改app.config文件,立即生效不用重启程序。现在用ConfigurationManager可以在app.config中写入新的值,但是必须要重启程序才能生效。我的代码如下:
<configuration>
<appSettings>
<add key="name" value="old"/>
</appSettings>
</configuration>
private void button1_Click(object sender, RoutedEventArgs e)
{
Console.WriteLine(ConfigurationManager.AppSettings["name"]);
ChangeConfiguration();
//刷新appSettings
ConfigurationManager.RefreshSection("appSettings");
Console.WriteLine(ConfigurationManager.AppSettings["name"]);
}
private static void ChangeConfiguration()
{
//读取程序集的配置文件
string assemblyConfigFile = Assembly.GetEntryAssembly().Location;
Configuration config = ConfigurationManager.OpenExeConfiguration(assemblyConfigFile);
//获取appSettings节点
AppSettingsSection appSettings = (AppSettingsSection)config.GetSection("appSettings");
//删除name,然后添加新值
appSettings.Settings.Remove("name");
appSettings.Settings.Add("name", "new");
//保存配置文件
config.Save();
}
现在是输出old old
怎么才能输出 old new, 展开
<configuration>
<appSettings>
<add key="name" value="old"/>
</appSettings>
</configuration>
private void button1_Click(object sender, RoutedEventArgs e)
{
Console.WriteLine(ConfigurationManager.AppSettings["name"]);
ChangeConfiguration();
//刷新appSettings
ConfigurationManager.RefreshSection("appSettings");
Console.WriteLine(ConfigurationManager.AppSettings["name"]);
}
private static void ChangeConfiguration()
{
//读取程序集的配置文件
string assemblyConfigFile = Assembly.GetEntryAssembly().Location;
Configuration config = ConfigurationManager.OpenExeConfiguration(assemblyConfigFile);
//获取appSettings节点
AppSettingsSection appSettings = (AppSettingsSection)config.GetSection("appSettings");
//删除name,然后添加新值
appSettings.Settings.Remove("name");
appSettings.Settings.Add("name", "new");
//保存配置文件
config.Save();
}
现在是输出old old
怎么才能输出 old new, 展开
2个回答
展开全部
你在config.Save() 后加这句试试:
ConfigurationManager.RefreshSection("appSettings");
ConfigurationManager.RefreshSection("appSettings");
追问
不是这个原因,把debug文件夹里的xxx.exe.vshost.config删除就好了
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询