c#中配置文件的使用(二)

来源:互联网 发布:虚空掠夺者数据库 编辑:程序博客网 时间:2024/05/20 20:47

1.在第一篇文章中,最后的自定义handler方法虽然可以实现,但是使用了2层的hashtable,看上去有点复杂。下面尝试使用property的方式 进行读取

配置文件如下:

<?xml version="1.0" encoding="utf-8" ?><configuration>  <configSections>    <section name="Person" type="Test3.PersonSection, Test3"/>  <!--类似于自定义handler的写法,其实就是要确认能找到自定义的section-->  </configSections>  <Person name="张三" age="27"/>      <!--定义的section的属性,这样使用的时候就不用定义hashtable了-->    <startup>         <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />    </startup></configuration>

下面是测试的代码

class Program    {        static void Main(string[] args)        {            var personSection = ConfigurationManager.GetSection("Person") as PersonSection;    //类似获取对应的节            if (personSection != null)                Console.WriteLine("name = {0}, age = {1}", personSection.Name, personSection.Age);  //直接获取节的属性            Console.ReadKey();        }    }    class PersonSection : ConfigurationSection   //继承自ConfigurationSection,然后才能使用相关的特性及方法。    {        [ConfigurationProperty("name", IsRequired = false, DefaultValue = "")]  //这个字段意义,具体的作用见之前关于自定义特性的相关的内容        public string Name        {            get { return (string) base["name"]; }    //这边属性的值的读写要调用base[]或者this[]            set { base["name"] = value; }        }        [ConfigurationProperty("age", IsRequired = false, DefaultValue = 0)]        public int Age        {            get { return (int) base["age"]; }            set { base["age"] = value; }        }    }
使用上面的方法,可以更方便根据自己想要的属性来设置初始值和加载。不像上一个例子中需要使用2个hashtable来解析配置值。

2. 配置元素的collection,上面自定义的一些配置节中,都只有一条信息,如果要实现一个配置节中有多条配置信息的话,就可以使用下面的方法

下面一步一步来实现,首先需要自定义集合中的元素,如下:

public class MyKeyValueSetting : ConfigurationElement       //表示集合中每个元素的组成方式,包含的属性    {        [ConfigurationProperty("name", IsRequired = true)]        public string Name        {            get { return this["name"].ToString(); }            set { this["name"] = value; }        }        [ConfigurationProperty("age", IsRequired = true)]        public string Age        {            get { return this["age"].ToString(); }            set { this["age"] = value; }        }        [ConfigurationProperty("height", IsRequired = true)]        public string Height        {            get { return this["height"].ToString(); }            set { this["height"] = value; }        }    }

定义了集合的包含的元素,则需要对集合作一个定义:

[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).Name;        }        // 说明:如果不需要在代码中修改集合,可以不实现Add, Clear, Remove,实现了这几个函数,就可以像appsettings中一样,在代码中修改相应的配置文件。        public void Add(MyKeyValueSetting setting)        {            this.BaseAdd(setting);        }        public void Clear()        {            base.BaseClear();        }        public void Remove(string name)        {            base.BaseRemove(name);        }    }
有了集合之后,自然就可以定义相应的配置节,根据节的名字来获取集合

public class PersonSection : 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];            }        }    }

下面是具体的测试方法和相应配置文件的写法:

class Program    {        static void Main(string[] args)        {            PersonSection mySection = ConfigurationManager.GetSection("PersonSection") as PersonSection;  //一样获取节点            if (mySection != null)                foreach (MyKeyValueSetting add in mySection.KeyValues)   //遍历节点中对应的集合中各个元素                {                    Console.WriteLine(add.Name + ":" + add.Age + " " + add.Height);   //打印出元素中的各个属性                }            Console.ReadKey();        }    }

配置文件:

<?xml version="1.0" encoding="utf-8" ?><configuration>  <configSections>    <section name="PersonSection" type="Test4.PersonSection, Test4" />  </configSections>  <PersonSection>                                           //这边的写法跟appsettings差不多了。可以同时自定义添加多个配置信息。    <add name="张三" age="25" height="170"></add>    <add name="李四" age="26" height="180"></add>    <add name="王二" age="27" height="190"></add>  </PersonSection>    <startup>         <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />    </startup></configuration>

因为在集合中有相关的对配置文件修改的操作,具体的操作方法可以参考前一篇文章中的方法在代码中对其配置文件进行修改。


上面2篇文章就是一些具体的对配置文件的简单操作,下一面会对c#中的 xml作一个比较详细的总结