Modify configuration section programmatically in medium trust
Asked Answered
B

1

3

I have a custom ConfigurationSection in my application:

public class SettingsSection : ConfigurationSection
{
    [ConfigurationProperty("Setting")]
    public MyElement Setting
    {
        get
        {
            return (MyElement)this["Setting"];
        }
        set { this["Setting"] = value; }
    }
}

public class MyElement : ConfigurationElement
{
    public override bool IsReadOnly()
    {
        return false;
    }

    [ConfigurationProperty("Server")]
    public string Server
    {
        get { return (string)this["Server"]; }
        set { this["Server"] = value; }
    }
}

In my web.config

  <configSections>
    <sectionGroup name="mySettingsGroup">
      <section name="Setting" 
               type="MyWebApp.SettingsSection"  
               requirePermission="false" 
               restartOnExternalChanges="true"
               allowDefinition="Everywhere"  />
    </sectionGroup>
  </configSections>

  <mySettingsGroup>
    <Setting>
      <MyElement Server="serverName" />
    </Setting>
  </mySettingsGroup>

Reading the section works fine. The issue I'm having is that when I read the section via

var settings = (SettingsSection)WebConfigurationManager.GetSection("mySettingsGroup/Setting");

And then I proceed to modify the Server property:

   settings.Server = "something";

This doesn't modify the "Server" property in the web.config file.

Note: This needs to work under medium-trust, so I can't use WebConfigurationManager.OpenWebConfiguration which works fine. Is there an explicit way to tell the ConfigSection to save itself?

Bigamous answered 30/1, 2011 at 8:39 Comment(0)
M
3

Short answer - no. .NET team were (allegedly) meant to fix this in v4, but it didn't happen.

The reason is because using WebConfigurationManager.GetSection returns nested read-only NameValueCollections, which do not persist when you change their values. Using WebConfigurationManager.OpenWebConfiguration, as you've quite rightly ascertained, is the only way to obtain read-write access to the config - but then you'll get a FileIOPermission exception thrown, as OpenWebConfiguration attempts to load all inherited configs down to your web.config - which include the machine-level web.config and machine.config files in C:\WINDOWS\Microsoft.NET\Framework, which are explicitly out-of-scope of Medium Trust.

Long answer - use XDocument / XmlDocument and XPath to get/set config values.

Midlothian answered 11/2, 2011 at 9:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.