.NET使用自定义配置部分创建自定义配置文件(获取错误)

时间:2014-01-23 16:05:41

标签: .net config configurationmanager

所以我有一个自定义配置文件如下:

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

1 个答案:

答案 0 :(得分:0)

事实证明,我需要覆盖此[int index]和此[string key]的ConfigurationElementCollection属性,以便直接访问元素。一旦我定义了那些,我就能使一切运转起来。