2014-01-23 54 views
0

所以我有一个自定义配置文件,如下所示:.NET创建一个自定义配置节(收到错误信息)的自定义配置文件

(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> 

而且我访问它如下:

(Default.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中使用此代码:

(Default.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功能来加载具有自定义配置部分的自定义配置并读取该数据。似乎这应该是一件困难的事情,但对于我的生活,我无法弄清楚。

+0

好了,解决了这个问题,我只需要在配置文件中指定程序集名称,例如:

然而,当foreach循环工作正常,试图做一个直接访问这样: x.ConnectionStrings [“SQLCE”] 给了我这个版本的错误: – Xorcist

+0

好,解决了这部分,结果发现我只需要在配置文件中指定程序集名称,例如: '

Xorcist

回答

0

原来,我需要覆盖此[int index]和[string key]的ConfigurationElementCollection属性,以便直接访问元素。一旦我定义了这些,我就可以让所有的工作都能正常工作