简体   繁体   English

编辑app.config文件并读取设置

[英]Edit app.config file and read settings

I have a app.config file. 我有一个app.config文件。 I have settings there. 我在那里设置。 I want to modify settings after my build and then read it from file. 我想在构建后修改设置,然后从文件中读取设置。 I mean I want to change settings by edeting a file. 我的意思是我想通过编辑文件来更改设置。 I know how to change settings programmaticaly but I need it by editing file. 我知道如何以编程方式更改设置,但是我需要通过编辑文件来更改。

No I'm trying to do so: 不,我正在尝试这样做:

    private void ReadSettings()
    {
        string appPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
        string settingsPath = Path.Combine(appPath, "app.config");
        ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
        configFileMap.ExeConfigFilename = settingsPath;
        System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
        string value=config.AppSettings.Settings["Type"].Value;
    }

My settings: 我的设置:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
            <section name="RxTest.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
        </sectionGroup>
    </configSections>
    <userSettings>
        <MyApp.Properties.Settings>
            <setting name="Type" serializeAs="String">
                <value>document</value>
            </setting>
        </RxTest.Properties.Settings>
    </userSettings>
</configuration>

Problem is that there is nothing in Settings property. 问题是“设置”属性中没有任何内容。

What shuld I do to read settings from edeted file? 我应该怎么做才能从已编辑的文件中读取设置?

The UserSettings written in your app.config file should be automatically added into it by adding an entry into your properties. 通过在属性中添加一个条目,应将app.config文件中编写的UserSettings自动添加到其中。

You can achieve getting the values from your properties like this: 您可以像这样从属性中获取值:

string value = Properties.Settings.Default.Type;


EDIT I: 编辑我:

To be sure you always have the freshest value, you can either refresh a section : 为确保始终拥有最新鲜的价值,您可以刷新以下部分

ConfigurationManager.RefreshSection(sectionName);

Or you can reaload the file: 或者您可以重新加载文件:

Properties.Settings.Default.Reload();

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

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