Modify configuration section programmatically in medium trust
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>
</configSectio开发者_如何学运维ns>
<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?
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 NameValueCollection
s, 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.
精彩评论