JoelFan
JoelFan

Reputation: 38714

can't cast to my custom ConfigurationSection

I'm trying to read a config file like this:

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");

I have ContentFolderSettings defined in the Corp.Common project and it inherits from ConfigurationSection. Here is the contents of 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>

But the line calling config.GetSection() is throwing InvalidCastException on:

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

Upvotes: 3

Views: 5988

Answers (2)

RckLN
RckLN

Reputation: 4484

tag is missing

In my case was this:

<configSections>

so you just add the tag

enter image description here

Upvotes: 5

user2903794
user2903794

Reputation: 69

Tag is missing .

Contains configuration section and namespace declarations.

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

Upvotes: 0

Related Questions