无法转换为我的自定义 ConfigurationSection
我正在尝试读取这样的配置文件:
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");
我在 Corp.Common
项目中定义了 ContentFolderSettings
,并且它继承自 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'.
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'.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
标签丢失
在我的例子中是这样的:
所以你只需添加标签
tag is missing
In my case was this:
so you just add the tag
标签丢失。
包含配置节和命名空间声明。
http://msdn.microsoft.com/en-我们/library/aa903350(v=vs.71).aspx
Tag is missing .
Contains configuration section and namespace declarations.
http://msdn.microsoft.com/en-us/library/aa903350(v=vs.71).aspx