简体   繁体   English

如何修改App.Config部分值

[英]How to modify the App.Config section value

I have an app.config like below, 我有一个像下面的app.config,

<configuration>
    <environment>
        <add key="security" value="1"/> -- I want to change this value to 3
    </environment>
</configuration>

I tried like below to get to environment section, 我试着去下面的环境部分,

Configuration config = ConfigurationManager.OpenExeConfiguration(exePath);
var environment = config.GetSection("environment");

environment variable doesn't give me enough options to get the child elements to modify the value. 环境变量没有给我足够的选项来让子元素修改值。 Could any one please help me out in this one. 有人可以帮我这个忙吗?

Use user scope settings!! 使用用户范围设置!! NEVER EVER change the application configuration that way. 永远不要以这种方式改变应用程序配置。 Any value that is changed within the application should be a user setting. 应用程序中更改的任何值都应该是用户设置。

Usually, you access these settings through 通常,您可以通过访问这些设置

Properties.Settings.Default.MyConfigurationValue = ....;
Properties.Settings.Default.Save();

EDIT 编辑
Sample for doing what I wrote in the comments. 做我在评论中写的示例。 Create two user settings: FirstRun is a bool which is by default set to true . 创建两个用户设置: FirstRun是一个bool ,默认情况下设置为true Environment is your value, by default set to 0 . Environment是您的值,默认设置为0

Then, for example in the Main function in Program.cs you'd do the following: 然后,例如在Program.csMain函数中,您将执行以下操作:

if (Properties.Settings.Default.FirstRun)
{
    Properties.Settings.Default.FirstRun = false;
    if (myConditionIsTrue)
        Properties.Settings.Default.Environment = 3;
    Properties.Settings.Default.Save();
}

Later in your application it is enough to use Properties.Settings.Default.Environment . 稍后在您的应用程序中使用Properties.Settings.Default.Environment就足够了。 That's how the settings mechanism is intended to be used if you want to change configuration values from your application. 如果要从应用程序更改配置值,那么就是如何使用设置机制。

Under Windows 2000, XP, 7 and the Windows Server branch you would not even have the rights to modify the app.config in your Program Files folder, so don't! 在Windows 2000,XP,7和Windows Server分支下,您甚至都没有权限修改Program Files文件夹中的app.config,所以请不要!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM