无法转换为我的自定义ConfigurationSection

时间:2011-11-30 02:50:08

标签: c# .net configuration-files

我正在尝试读取这样的配置文件:

var dllPath =  System.IO.Path.GetDirectoryName(System.Reflection.Assembly.
    GetExecutingAssembly().GetName().CodeBase);
dllPath = dllPath.Replace("file:\\", string.Empty);
var configPath = string.Format(@"{0}\..\contentFolders.config", dllPath);
var fileMap = new ExeConfigurationFileMap() {ExeConfigFilename = configPath};
var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, 
    ConfigurationUserLevel.None);
var contentFolderConfig = 
    (ContentFolderSettings)config.GetSection("contentFolderConfiguration");

我在ContentFolderSettings项目中定义了Corp.Common,它继承自ConfigurationSection。以下是contentFolders.config

的内容
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <section name="contentFolderConfiguration"
    type="Corp.Common.ContentFolderSettings, Corp.Common"
    requirePermission="false"/>
  <contentFolderConfiguration>
    <contentFolders>
      <contentFolder key="ImagesFolder" path="content\images"/>
      <contentFolder key="CssFolder" path="content\css"/>
      ...
    </contentFolders>
  </contentFolderConfiguration>
</configuration>

但是,调用config.GetSection()的行正在抛出InvalidCastException

Unable to cast object of type 'System.Configuration.DefaultSection' to type 
'Corp.Common.ContentFolderSettings'.

2 个答案:

答案 0 :(得分:5)

标记缺失

就我而言:

<configSections>

所以你只需添加标签

enter image description here

答案 1 :(得分:0)

标签丢失。

包含配置节和名称空间声明。

http://msdn.microsoft.com/en-us/library/aa903350(v=vs.71).aspx