读取.config文件的各种方式

1,首先在Web.config中配置节点;

 <configSections>
    <section name="MySection111" type="WebApplication1.model.MySection1"/>
    <section name="MySection222" type="WebApplication1.model.MySection2"/>
    <section name="MySection333" type="WebApplication1.model.MySection3"/>
    <section name="MySection444" type="WebApplication1.model.MySection4"/>
  </configSections>

<MySection111 username="luoxufeng测试" url="http://www.test.com"></MySection111>
  <MySection222>
    <testusers username="alice" password="12345678"></testusers>
  </MySection222>
  
  <MySection333>
    <Command1>
      <![CDATA[
            create procedure ChangeProductQuantity(
                @ProductID int,
                @Quantity int
            )
            as
            update Products set Quantity = @Quantity 
            where ProductID = @ProductID;
        ]]>
    </Command1>
    <Command2>
      <![CDATA[
            create procedure DeleteCategory(
                @CategoryID int
            )
            as
            delete from Categories
            where CategoryID = @CategoryID;
        ]]>
    </Command2>
  </MySection333>
  <MySection444>
    <add key="aa" value="11111"></add>
    <add key="bb" value="22222"></add>
    <add key="cc" value="33333"></add>
  </MySection444>

 //第一种节点配置读取
            MySection1 mySectioin1 = (MySection1)ConfigurationManager.GetSection("MySection111");
            this.txtusername.Value = mySectioin1.UserName;
            this.txturl.Value = mySectioin1.Url;
            Url = mySectioin1.Url;

定义MySection1类;
 public class MySection1 : ConfigurationSection
    {
        /*
         1. 自定义一个类,以ConfigurationSection为基类,各个属性要加上[ConfigurationProperty] ,ConfigurationProperty的构造函数中传入的name字符串将会用于config文件中,表示各参数的属性名称。
         2. 属性的值的读写要调用this[],由基类去保存,请不要自行设计Field来保存。
         3. 为了能使用配置节点能被解析,需要在<configSections>中注册: <section name="MySection111" type="RwConfigDemo.MySection1, RwConfigDemo" /> ,且要注意name="MySection111"要与<MySection111 ..... >是对应的。 
         */
        [ConfigurationProperty("username", IsRequired = true)]
        public string UserName
        {
            get { return this["username"].ToString(); }
            set { this["username"] = value; }
        }

        [ConfigurationProperty("url", IsRequired = true)]
        public string Url
        {
            get { return this["url"].ToString(); }
            set { this["url"] = value; }
        }
    }


//第二种节点配置读取
            MySection2 mySection2 = (MySection2)ConfigurationManager.GetSection("MySection222");
            this.txtusername2.Value = mySection2.TestUsers.UserName;
            this.txtpassword2.Value = mySection2.TestUsers.Password;

自定义两个类;
public class MySection2 : ConfigurationSection
    {
        [ConfigurationProperty("testusers", IsRequired = true)]
        public MySectionElement TestUsers
        {
            get { return (MySectionElement)this["testusers"]; }        
        }
    }

    public class MySectionElement : ConfigurationElement
    {
        [ConfigurationProperty("username", IsRequired = true)]
        public string UserName
        {
            get { return this["username"].ToString(); }
            set { this["username"] = value; }
        }

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


    //第三种节点配置读取
            MySection3 mySection3 = (MySection3)ConfigurationManager.GetSection("MySection333");
            this.txtContent1.Value = mySection3.Command1.CommandText;
            this.txtContent2.Value = mySection3.Command2.CommandText;
自定义相关类;
 public class MySection3:ConfigurationSection
    {
        [ConfigurationProperty("Command1", IsRequired = true)]
        public MyTextElement Command1
        {
            get { return (MyTextElement)this["Command1"]; }
        }

        [ConfigurationProperty("Command2", IsRequired = true)]
        public MyTextElement Command2
        {
            get { return (MyTextElement)this["Command2"]; }
        }
    }

    public class MyTextElement : ConfigurationElement
    {
        protected override void DeserializeElement(System.Xml.XmlReader reader, bool serializeCollectionKey)
        {
            CommandText = reader.ReadElementContentAs(typeof(string), null) as string;
        }

        protected override bool SerializeElement(System.Xml.XmlWriter writer, bool serializeCollectionKey)
        {
            if (writer != null)
                writer.WriteCData(CommandText);
            return true;
        }

        [ConfigurationProperty("data", IsRequired = false)]
        public string CommandText
        {
            get { return this["data"].ToString(); }
            set { this["data"] = value; }
        }
    }


   //第四种节点配置读取
            MySection4 mySection4 = (MySection4)ConfigurationManager.GetSection("MySection444");
            txtKeyValues.Value = string.Join("\r\n",(from kv in mySection4.KeyValues.Cast<MyKeyValueSetting>()
                                                      let s = string.Format("{0}={1}", kv.Key, kv.Value)
                                                      select s).ToArray());



//自定义相关类;
  public class MySection4:ConfigurationSection
    {
        private static readonly ConfigurationProperty s_property 
            = new ConfigurationProperty(string.Empty,typeof(MyKeyValueCollection),null,ConfigurationPropertyOptions.IsDefaultCollection);

         [ConfigurationProperty("", Options = ConfigurationPropertyOptions.IsDefaultCollection)]
        public MyKeyValueCollection KeyValues
        {
            get
            {
                return (MyKeyValueCollection)base[s_property];
            }
        }
    }

    //自定义一个集合类
    [ConfigurationCollection(typeof(MyKeyValueSetting))]
    public class MyKeyValueCollection : ConfigurationElementCollection
    {
          // 基本上,所有的方法都只要简单地调用基类的实现就可以了。
       public MyKeyValueCollection():base(StringComparer.OrdinalIgnoreCase)
       {
       }

         // 其实关键就是这个索引器。但它也是调用基类的实现,只是做下类型转就行了。
        new public MyKeyValueSetting this[string name]
        {
            get
            {
              return (MyKeyValueSetting)base.BaseGet(name);
            }
        }

         // 下面二个方法中抽象类中必须要实现的。
        protected override ConfigurationElement CreateNewElement()
        {
            return new MyKeyValueSetting();
        }
        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((MyKeyValueSetting)element).Key;
        }

        // 说明:如果不需要在代码中修改集合,可以不实现Add, Clear, Remove
        public void Add(MyKeyValueSetting setting)
        {
            this.BaseAdd(setting);
        }
        public void Clear()
        {
            base.BaseClear();
        }
        public void Remove(string name)
        {
            base.BaseRemove(name);
        }
    }

    //集合中的每个元素
    public class MyKeyValueSetting:ConfigurationElement
    {
        [ConfigurationProperty("key", IsRequired = true)]
        public string Key
        {
           get {return this["key"].ToString();}
           set{this["key"]=value;}
        }

        [ConfigurationProperty("value", IsRequired = true)]
        public string Value
        {
            get {return this["value"].ToString();}
            set {this["value"]=value;}
        }
    }








  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值