写在外部文件的appSettings [英] Write appSettings in external file

查看:142
本文介绍了写在外部文件的appSettings的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个配置文件app.exe.config和的appSettings节有这样的事情:

I have a config file app.exe.config and appSettings section has something like this:

<configuration>
    <appSettings configSource="app.file.config" />
</configuration>

app.file.config文件中有这样的事情:

app.file.config file has something like this:

<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
  <add key="var1" value="value 1" />
  <add key="var2" value="value 2" />
  <add key="var3" value="value 3" />
</appSettings>

我需要编辑VAR1,VAR2和VAR3在运行时,我有code是这样的:

I need to edit var1, var2 and var3 at runtime and I have code like this:

Configuration config = ConfigurationManager.OpenExeConfiguration("...path\app.exe);

config.AppSettings.SectionInformation.ConfigSource = "app.file.config";

config.AppSettings.Settings["var1"].Value = "value 11";
config.AppSettings.Settings["var2"].Value = "value 22";
config.AppSettings.Settings["var3"].Value = "value 33";
config.Save(ConfigurationSaveMode.Modified);

ConfigurationManager.RefreshSection("appSettings");

当我运行config.Save ....文件app.file.config具有属性的file的appSettings节点。该属性的值app.file.config

When I run config.Save.... the file app.file.config has a appSettings node with an attribute "file". This attribute has the value to app.file.config

<appSettings file="app.file.config">
<add key="var1" value="value 1" />
  <add key="var2" value="value 2" />
  <add key="var3" value="value 3" />
</appSettings>

现在,如果我尝试加载配置文件,我有一个异常的消息无法识别的属性'文件'。请注意,属性名称是区分大小写的。在app.file.config。

Now, if I try to load the config file, I have an exception with message "Unrecognized attribute 'file'. Note that attribute names are case-sensitive." in app.file.config.

如果我手动删除该文件的属性,配置文件加载正确。

If I delete the file attribute manually, the configuration file is loaded properly.

任何想法?

如何才能避免写文件属性的时候我保存配置文件。

How can avoid to write file attribute when I save config files.

感谢

推荐答案

最后,我已经找到了解决办法。

Finally, I have found a solution.

解决的办法是声明的配置文件,如下:

The solution is to declare the config file as this:

<appSettings configSource="app.file.config">
<add key="var1" value="value 1" />
  <add key="var2" value="value 2" />
  <add key="var3" value="value 3" />
</appSettings>

和从code

Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
AppSettingsSection myAppSettings = config.GetSection("appSettings")
myAppSettings.Settings["var1"].Value = "value 11";
config.Save(ConfigurationSaveMode.Modified);

请注意,我用     GetSection(的appSettings) 代替     config.AppSettings.Settings

Note that I use GetSection("appSettings") instead of config.AppSettings.Settings

感谢所有帮助人们计算器。

Thanks to all that help people in StackOverflow.

这篇关于写在外部文件的appSettings的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆