Web.Config:ConfigurationSection 使用示例

ConfigurationSection类主要是方便我们用于扩展自定义webcongfig中的节点信息。我们可以方便的通过以下方式获取【自定义节点对象】

【你自定义的对象】 config = (【你自定义的对象】)ConfigurationManager.GetSection("【你自定义的节点名称,如果是sectiongroup的话,请使用XPATH方式】");

使用自定义节点,可能会涉及到这几个对象的使用:ConfigurationSection【配置域】、ConfigurationElement【节点】、ConfigurationElementCollection【节点列表】

用法一: 配置如下webconfig自定义信息,注意order和lineItem节点都是允许重复出现的 

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="orders" type="ConsoleTest.OrdersSection, ConsoleTest"/>
  </configSections>
  <orders companyID="2001">
    <order number="100001" amount="222.22">
      <lineItems warehouseNumber="02">
        <lineItem number="00-000-001" description="wii"/>
      </lineItems>
    </order>
    <order number="300001" amount="33.33">
      <lineItems warehouseNumber="99">
        <lineItem number="00-000-001" description="xbox 360"/>
        <lineItem number="00-000-003" description="playstation 3"/>
      </lineItems>
    </order>
  </orders>
</configuration>


下面我们要定义相应的实体对象,该实体对象中会有一个子对象【用来表示节点列表信息】(ConfigurationElementCollection)

public class OrdersSection : ConfigurationSection
    {
        [ConfigurationProperty("companyID", IsRequired = true)]
        public string CompanyID
        {
            get
            {
                return (string)base["companyID"];
            }
            set
            {
                base["companyID"] = value;
            }
        }

        [ConfigurationProperty("", IsDefaultCollection = true)]
        public OrderElementCollection Orders
        {
            get
            {
                return (OrderElementCollection)base[""];
            }
        }
    }


接下来我们在看看节点列表对象的定义,其中会包含一个子对象【ConfigurationElementCollection】

public class OrderElementCollection : ConfigurationElementCollection
    {
        protected override ConfigurationElement CreateNewElement()
        {
            return new OrderElement();
        }
        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((OrderElement)element).Number;
        }

        public override ConfigurationElementCollectionType CollectionType
        {
            get
            {
                return ConfigurationElementCollectionType.BasicMap;
            }
        }
        protected override string ElementName
        {
            get
            {
                return "order";
            }
        }

        public OrderElement this[int index]
        {
            get
            {
                return (OrderElement)BaseGet(index);
            }
            set
            {
                if (BaseGet(index) != null)
                {
                    BaseRemoveAt(index);
                }
                BaseAdd(index, value);
            }
        }
    }


那么我们再看看节点对象的定义

public class OrderElement : ConfigurationElement
    {
        [ConfigurationProperty("number", IsRequired = true)]
        public string Number
        {
            get
            {
                return (string)base["number"];
            }
            set
            {
                base["number"] = value;
            }
        }

        [ConfigurationProperty("amount", IsRequired = true)]
        public double Amount
        {
            get
            {
                return (double)base["amount"];
            }
            set
            {
                base["amount"] = value;
            }
        }

        [ConfigurationProperty("lineItems", IsDefaultCollection = true)]
        public LineItemElementCollection LineItems
        {
            get
            {
                return (LineItemElementCollection)base["lineItems"];
            }
        }
    }


另外,还有一个子节点列表对象需要定义,【LineItemElementCollection】(ConfigurationElementCollection)

public class LineItemElementCollection : ConfigurationElementCollection
    {
        [ConfigurationProperty("warehouseNumber", IsRequired = true)]
        public string WarehouseNumber
        {
            get
            {
                return (string)base["warehouseNumber"];
            }
            set
            {
                base["warehouseNumber"] = value;
            }
        }

        protected override ConfigurationElement CreateNewElement()
        {
            return new LineItemElement();
        }
        protected override object GetElementKey(ConfigurationElement element)
        {
            return ( (LineItemElement)element ).Number;
        }

        public override ConfigurationElementCollectionType CollectionType
        {
            get
            {
                return ConfigurationElementCollectionType.BasicMap;
            }
        }
        protected override string ElementName
        {
            get
            {
                return "lineItem";
            }
        }

        public LineItemElement this[int index]
        {
            get
            {
                return (LineItemElement)BaseGet(index);
            }
            set
            {
                if (BaseGet(index) != null)
                {
                    BaseRemoveAt(index);
                }
                BaseAdd(index, value);
            }
        }
    }


 

当然我们还得再定义一个节点对象【LineItemElement

public class LineItemElement : ConfigurationElement
    {
        [ConfigurationProperty("number", IsKey=true, IsRequired = true)]
        public string Number
        {
            get
            {
                return (string)base["number"];
            }
            set
            {
                base["number"] = value;
            }
        }

        [ConfigurationProperty("description", IsRequired = true)]
        public string Description
        {
            get
            {
                return (string)base["description"];
            }
            set
            {
                base["description"] = value;
            }
        }
    }


 

这样我们就完成了webconfig节点的自定义和对象的实体化, 我们在使用的使用值需要简单的代码就能获取到相应对象的实体信息;如:

OrdersSection  config = (OrdersSection)ConfigurationManager.GetSection("orders");

 

另一中用法:sectionGroup 配置 。如要配置出如下webconfig信息

<configSections>
    <sectionGroup name="mygroup">
      <section name="mysection"
                       type="ConfigSection"
                        allowDefinition="Everywhere"
                         allowLocation="true"/>
    </sectionGroup>
  </configSections>

  <mygroup>
    <mysection  user="用户" password="密码">
      <element element1="属性1" element2="属性2"></element>
    </mysection>
  </mygroup>


那么我们看下实体是如何定义的 。

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// ConfigSection 的摘要说明
/// </summary>
public class ConfigSection:ConfigurationSection
{
    public ConfigSection()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }
[ConfigurationProperty("user",DefaultValue="yanghong",IsRequired=true)]
    public string User
    {
        get { return (string)this["user"]; }
        set { this["user"] = value; }
    }

    [ConfigurationProperty("password",DefaultValue="password",IsRequired=true)]
    public string PassWord
    {
        get {  return (string)this["password"]; }
        set { this["password"] = value; }
    }

    [ConfigurationProperty("element")]
    public elementinfo Element
    {
        get { return  (elementinfo)this["element"]; }
        set {this["element"] = value; }
    }
}


上面的实体对象包含一个节点对象信息,我们看下这个对象是如何定义的 。

public class elementinfo : ConfigurationElement
{
    public elementinfo()    { }


    [ConfigurationProperty("element1", DefaultValue = "element1", IsRequired = true)]
    public string Element1
    {
        get { return (string)this["element1"]; }
    }

    [ConfigurationProperty("element2",DefaultValue="element2",IsRequired=true)]
    public string Element2
    {
        get { return (string)this["element2"]; }
    }


}


 

代码的调用就相当简单了 :

ConfigSection config = (ConfigSection)ConfigurationManager.GetSection("mygroup/mysection");
    Response.Write("用户名:"+config.User.ToString() + "密码:" + config.PassWord.ToString() + "元素属性:" + config.Element.Element1.ToString() + config.Element.Element2.ToString());


 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 C# 中,你可以使用 `System.Configuration.ConfigurationManager` 类来读取 `config.ini` 配置文件中的数据。下面是一个简单的示例: 1. 首先,确保你的项目中已经添加了 `System.Configuration` 引用。你可以在 Visual Studio 中右键点击项目,选择“添加”->“引用”,然后在“框架”中找到 `System.Configuration` 并添加。 2. 在项目根目录下创建一个 `config.ini` 文件,并填写相关配置项。 3. 在代码中使用 `ConfigurationManager` 类读取配置项。下面是一个简单的示例: ```csharp using System.Configuration; // 读取数据库连接字符串 string connectionString = ConfigurationManager.AppSettings["databaseConnectionString"]; ``` 在上面的示例中,我们使用 `ConfigurationManager.AppSettings` 方法读取了 `config.ini` 文件中名为 `databaseConnectionString` 的配置项。 如果你需要读取的是一个自定义的配置节,可以使用 `ConfigurationManager.GetSection` 方法。例如: ```csharp // 读取服务器配置 ServerConfigSection serverConfig = ConfigurationManager.GetSection("server") as ServerConfigSection; ``` 在上面的示例中,我们读取了 `config.ini` 文件中名为 `server` 的配置节,并将其转换为自定义的 `ServerConfigSection` 类型。需要注意的是,你需要自己定义 `ServerConfigSection` 类型,并在其中定义与配置项对应的属性。例如: ```csharp public class ServerConfigSection : ConfigurationSection { [ConfigurationProperty("ip", IsRequired = true)] public string Ip { get { return (string)this["ip"]; } set { this["ip"] = value; } } [ConfigurationProperty("port", IsRequired = true)] public int Port { get { return (int)this["port"]; } set { this["port"] = value; } } } ``` 在上面的示例中,我们定义了一个 `ServerConfigSection` 类型,其中包含了 `ip` 和 `port` 两个属性,分别对应 `config.ini` 文件中的 `ip` 和 `port` 配置项。使用 `ConfigurationProperty` 特性来标记属性对应的配置项,并在属性的 getter 和 setter 中读取和设置配置项的值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值