【问题标题】:How to add custom section in app. config file如何在应用程序中添加自定义部分。配置文件
【发布时间】:2013-11-16 16:55:02
【问题描述】:

这是我的app.config 文件

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <configSections>
      <section name="customSettings" type="ConsoleApplication6.Class1,ConsoleApplication6 "/>
   </configSections>

   <customSettings>
      <name>mala</name> 
   </customSettings>
</configuration>

C#代码,实现create方法IConfigurationSectionHandler接口

namespace ConsoleApplication6
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Xml;


public class Class1
{
    public string name;
    public string Name
    {
        get { return this.name; }
        set { this.name=value;}
    }

    public class configH : IConfigurationSectionHandler
    {
        public configH() { }

        public object Create(object parent, object configContext, System.Xml.XmlNode section)
        {
            Class1 cl = new Class1();
            cl.name = section.SelectSingleNode("name").InnerText;
            return cl;
        }
    }
}

主程序

namespace ConsoleApplication6
{
  class Program
  {
    static void Main(string[] args)
    {
        Class1 settings = (Class1)ConfigurationManager.GetSection("customSettings");
        Console.WriteLine(settings.name);
    }
}

但运行时出现错误

为 customSettings 创建配置节处理程序时出错:类型“ConsoleApplication6.Class1”不继承自“System.Configuration.IConfigurationSectionHandler”

我不确定app.config 文件中section 标记中的type 属性。我用过TYPE=classname,namespacename

【问题讨论】:

    标签: c#


    【解决方案1】:

    使用这个sample

    <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>
    

    【讨论】:

    • 感谢您的回答。但我发现很难获得公共令牌 ID。我在 Visual Studio toos-> 外部工具中尝试过。但没有像“Get &PublicKeyToken”这样的东西
    猜你喜欢
    • 2010-11-06
    • 2021-10-24
    • 2010-12-13
    • 1970-01-01
    • 1970-01-01
    • 2012-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多