如何在应用程序中添加自定义部分。配置文件

时间:2013-11-16 03:57:18

标签: c#

这是我的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#代码,实现了创建方法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

1 个答案:

答案 0 :(得分:0)

使用此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>