2014-01-23 57 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屬性,以便直接訪問元素。一旦我定義了這些,我就可以讓所有的工作都能正常工作