【发布时间】:2014-02-14 07:26:03
【问题描述】:
所以我有一个自定义配置文件如下:
(myConfig.cfg)
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="wcfSettings" type="Maxeta.Services.Configuration.maxServiceSection"/>
</configSections>
<wcfSettings>
<connectionStrings>
<add name="SQLL3" connectionString="Data Source=|DataDirectory|Test.db; Version=3; New=False; Compress=False;" providerName="System.Data.SQLite" databaseDialect="Standard"/>
<add name="SQLCE" connectionString="Data Source=|DataDirectory|Test.sdf; Max Database Size=256; Persist Security Info=False;" providerName="System.Data.SqlServerCe.4.0" databaseDialect="Standard" />
<add name="MSSQL" connectionString="Data Source=127.0.0.1; Initial Catalog=Test; Persist Security Info=true; User ID=****; PWD=****;" providerName="System.Data.SqlClient" databaseDialect="MsSql2005" />
</connectionStrings>
</wcfSettings>
</configuration>
我访问它的方式如下:
(默认.aspx.cs)
protected void Page_Load(object sender, EventArgs e) {
String cfg = String.Format("{0}myConfig.cfg", HttpRuntime.AppDomainAppPath);
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap() { ExeConfigFilename = cfg }, ConfigurationUserLevel.None);
maxServiceSection section = config.GetSection("wcfSettings") as maxServiceSection;
foreach (maxServiceElement element in section.ConnectionStrings) {
ltrText.Text += String.Format("{0}<br/>", element.DatabaseDialect);
}
}
我得到的错误是:
An error occurred creating the configuration section handler for wcfSettings: Could not load type 'Maxeta.Services.Configuration.maxServiceSection' from assembly 'System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. (C:\Users\JHorvath\Documents\Visual Studio 2010\Examples\WebSite\C#\CustomConfig\CustomConfig\myConfig.cfg line 4)
但是,如果我不从单独的文件中加载它,并将 web.config 与此代码一起使用:
(默认.aspx.cs)
protected void Page_Load(object sender, EventArgs e) {
maxServiceSection section = ConfigurationManager.GetSection("wcfSettings") as maxServiceSection;
foreach (maxServiceElement element in section.ConnectionStrings) {
ltrText.Text += String.Format("{0}<br/>", element.DatabaseDialect);
}
}
一切正常...有人可以解释如何使用内置的 ConfigurationManager.OpenMappedExeConfiguration 功能来加载具有自定义配置部分的自定义配置并读取该数据。看起来这应该是一件很难的事情,但对于我的生活,我无法弄清楚。
【问题讨论】:
-
好的,解决了部分问题,原来我只需要在配置文件中指定程序集名称: 但是,虽然 foreach 循环工作正常,但尝试直接访问:x.ConnectionStrings["SQLCE"] 给我这个构建错误:
-
好的,解决了部分问题,原来我只需要在配置文件中指定程序集名称,如下所示:'' 但是,虽然 foreach 循环工作正常,但尝试直接访问单个元素:'((maxServiceElement)config.ConnectionStrings["SQLCE"]).databaseDialect;'给我这个构建错误:'System.Configuration.ConfigurationElement.this[System.Configuration.ConfigurationProperty] 由于其保护级别而无法访问'
标签: .net config configurationmanager