简体   繁体   中英

Edit app.config file and read settings

I have a app.config file. 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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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