C# App.config-自定义节不工作
我最近开始构建web应用程序的控制台版本。我从web.config复制了自定义部分。到我的app.config。当我获取配置信息时,会出现以下错误: 创建x/y的配置节处理程序时出错:无法从程序集“System.configuration”加载类型“x” 它不喜欢的一句话是: 将ConfigurationManager.GetSection(“X/Y”)返回为Z 有人碰到这样的事吗 我可以补充说C# App.config-自定义节不工作,c#,C#,我最近开始构建web应用程序的控制台版本。我从web.config复制了自定义部分。到我的app.config。当我获取配置信息时,会出现以下错误: 创建x/y的配置节处理程序时出错:无法从程序集“System.configuration”加载类型“x” 它不喜欢的一句话是: 将ConfigurationManager.GetSection(“X/Y”)返回为Z 有人碰到这样的事吗 我可以补充说 <add key="IsReadable" value="0"/> 在appSe
<add key="IsReadable" value="0"/>
在appSettings中打开并阅读它
补充:
我确实对自定义部分进行了定义:
<configSections>
<sectionGroup name="x">
<section name="y" type="zzzzz"/>
</sectionGroup>
</configSections>
听起来您的配置节处理程序没有定义
<configSection>
<section
name="YOUR_CLASS_NAME_HERE"
type="YOUR.NAMESPACE.CLASSNAME, YOUR.NAMESPACE, Version=1.1.0.0, Culture=neutral, PublicKeyToken=PUBLIC_TOKEN_ID_FROM_ASSEMBLY"
allowLocation="true"
allowDefinition="Everywhere"
/>
</configSection>
如果需要自定义配置处理程序,必须定义类并引用它,如Steven Lowe所示。您可以从预定义的处理程序继承,也可以只使用appSetting节中提供的值/密钥对(如您所述)。在文件顶部,您需要在节内具有configSection标记
你也可以有一个小组。例如:
<configuration>
<configSections>
<sectionGroup name="x">
<section name="y" type="a, b"/>
</sectionGroup>
<configSections>
</configuration>
此类用作任何类型的通用自定义配置节处理程序
public class XmlConfigurator : IConfigurationSectionHandler
{
public object Create(object parent, object configContext, XmlNode section)
{
if (section == null) return null;
Type sectionType = Type.GetType((string)(section.CreateNavigator()).Evaluate("string(@configType)"));
XmlSerializer xs = new XmlSerializer(sectionType);
return xs.Deserialize(new XmlNodeReader(section));
}
}
在app.config中,添加
<section name="NameofConfigSection" type="NameSpace.XmlConfigurator, NameSpace.Assembly"/>
在configuration部分元素中,添加一个属性来指定要反序列化根元素的类型
<?xml version="1.0" encoding="utf-8" ?>
<NameofConfigSection configType="NameSpace.NameofTypeToDeserializeInto, Namespace.Assembly" >
...
</NameofConfigSection>
...
我最近也遇到了同样的问题。我为一个web应用程序创建了一个自定义的sectiongroup(运行良好),但是当我将这个层移植到一个控制台应用程序时,sectiongroup失败了
您的问题是正确的,关于在您的节定义中需要多少“类型”。我已使用以下示例修改了您的配置部分:
<configSection>
<section
name="yourClassName"
type="your.namespace.className, your.assembly"
allowLocation="true"
allowDefinition="Everywhere" />
</configSection>
您会注意到,现在该类型的类名后跟程序集名。这是在web环境之外进行交互所必需的
注意:程序集名称不一定等于您的命名空间(对于给定的节)。需要多少类型节?您不需要区域性和公钥来解决问题。请检查下面我的简短版本。@Daok:我只是在听命令!;-).NET 2.0及更高版本中不推荐使用IConfigurationSectionHandler。改为从ConfigurationSection继承。但是,据我所知,您不能使用更新的方法复制上述代码提供的功能(即,能够使用相同的“通用”处理程序反序列化任何配置secrion)。。。使用ConfigurationSection,您必须为每个要反序列化的新配置节编写一个新的、不同的派生类。。。