简体   繁体   中英

change a config value in tets project's app.config file

i'm trying to test some functionality which is dependant on a configuration value (if Settings["foo"] = true than return 5, otherwise- return -1).

So what I'm trying to do is to change the configuration value at runtime.
my config file looks like so (simplified):

    <configSections>
      <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">      
        <section name="DomainSettings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
      </sectionGroup>
    </configSections>

<applicationSettings>
<DomainSettings>
    <setting name="foo" serializeAs="String">
      <value>false</value>
    </setting>
</ICTS.SmartQueue.Domain.DomainSettings>
</applicationSettings>

and I'm doing the following:

//get config file
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
//get relevant section
var section = (ClientSettingsSection)config.GetSection("applicationSettings/DomainSettings");
//get element from section
var element = section.Settings.Get("Foo"); 
//change its value and save it
element.Value.ValueXml.InnerText = true.ToString();
config.Save(System.Configuration.ConfigurationSaveMode.Modified, true);
//force refresh
ConfigurationManager.RefreshSection("applicationSettings/DomainSettings");

I can see that the value is actually changed when I look at the test's config file in the 'Out' directory (MyTests.DLL.config).
However, DomainSettings.Default.Foo still evaluates to 'false'.

any ideas?

The config file is cached. In other words, just because you modify the config file with a new value, it will not reload until the application reloads. Then, you will see the new value changed. But when you reference the config file in your code, it doesn't read the file, it reads the config that is cached. And in your case, that is not updated with your new value.

That's because you can change the config file at runtime but the changes won't be picked up until you restart the app. ASP.NET is different, it will pick up the changes immediately after the Web.config file changes.

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