我的应用程序中有一个自定义 ConfigurationSection:
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; }
}
}
在我的 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>
阅读该部分效果很好。我遇到的问题是,当我通过以下方式阅读该部分时
var settings = (SettingsSection)WebConfigurationManager.GetSection("mySettingsGroup/Setting");
然后我继续修改Server
财产:
settings.Server = "something";
这不会修改 web.config 文件中的“服务器”属性。
注意:这需要在中等信任下工作,所以我不能使用WebConfigurationManager.OpenWebConfiguration
效果很好。有没有明确的方式告诉ConfigSection
为了拯救自己?
简短的回答 - 不。 .NET 团队(据称)打算在 v4 中修复此问题,但没有发生。
原因是因为使用WebConfigurationManager.GetSection
返回嵌套只读NameValueCollection
s,当您更改其值时,它们不会持续存在。使用WebConfigurationManager.OpenWebConfiguration
正如您已经完全正确地确定的那样,是获得对配置的读写访问权限的唯一方法 - 但随后您将得到FileIOPermission
抛出异常,如OpenWebConfiguration
尝试将所有继承的配置加载到您的 web.config - 其中包括计算机级别的 web.config 和 machine.config 文件C:\WINDOWS\Microsoft.NET\Framework
,这显然超出了 Medium Trust 的范围。
长答案 - 使用XDocument
/ XmlDocument
和 XPath 来获取/设置配置值。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)