自定义配置文件的使用(web.config/app.config)

时间:2021-07-31 15:32:11

(1)只需要简单配置单一属性值:

 <configuration>
<configSections>
<!--配置读取的全名称-->
<section name="simple" type="ConfigNode.SimpleSection,ConfigNode"/>
</configSections>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<!--自定义单一数据-->
<simple maxValue="" minValue=""></simple>
</configuration>

要获取在配置文件中自定义的值,此时在我们上面配置的ConfigNode.SimpleSection,ConfigNode,根据这个创建SimpleSection类,在其中写上获取此节点的属性

  public class SimpleSection : ConfigurationSection//必须要继承这个类
{
/// <summary>
/// 实例化配置属性 元素是否必须 默认值
/// </summary>
[ConfigurationProperty("maxValue", IsRequired = false, DefaultValue = Int32.MaxValue)]
public int MaxValue
{
get
{
//配置文件中的节
return (int)base["maxValue"];
}
set
{
base["maxValue"] = value;
}
}
[ConfigurationProperty("minValue", IsRequired = false, DefaultValue = )]
public int MinValue
{
get { return (int)base["minValue"]; }
set { base["minValue"] = value; }
}
}

使用:

 SimpleSection simple = ConfigurationManager.GetSection("simple") as SimpleSection;
int maxValue = simple.MaxValue;
int minValue = simple.MinValue;

(2)在配置节点的头部,我们也需要配置一个属性值的话

 <configSections>
<section name="colors" type="ConfigNode.ColorsSection,ConfigNode" />
</configSections>
<colors type="颜色">
<color id="skyblue" name="天蓝色"/>
</colors>

ColorsSection类:

 public class ColorsSection : ConfigurationSection
{
[ConfigurationProperty("type", IsRequired = true)]
public string Type
{
get
{
return (string)base["type"];
}
set
{
base["type"] = value;
}
}
[ConfigurationProperty("color", IsDefaultCollection = false)]
public ColorSection Color
{
get
{
return (ColorSection)base["color"];
}
set
{
base["color"] = value;
}
} } public class ColorSection : ConfigurationElement
{
[ConfigurationProperty("id", IsRequired = true, IsKey = true)]
public string Id
{
get
{
return (string)base["id"];
}
set
{
base["id"] = value;
}
}
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get
{
return (string)base["name"];
}
set
{
base["name"] = value;
}
}
}

使用和第一的相同

(3)配置多个节点:

 configuration>
<configSections>
<!--这里name的名字 必须与创建的类的名字相同-->
<section name="AnimalSection" requirePermission="false" type="ConfigNode.AnimalSection,ConfigNode"/>
</configSections> <system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<!--这里的也是-->
<AnimalSection>
<add cname="小狗" ename="dog" />
<add cname="小猫" ename="cat" />
<add cname="小兔" ename="rabbit" />
</AnimalSection>

AnimalSection类:

 // 所有配置节点都要选择这个基类  ConfigurationSection
public class AnimalSection : ConfigurationSection
{ private static readonly ConfigurationProperty s_property = new ConfigurationProperty(string.Empty, typeof(AnimalCollect), null, ConfigurationPropertyOptions.IsDefaultCollection);
[ConfigurationProperty("", Options = ConfigurationPropertyOptions.IsDefaultCollection)]
public AnimalCollect ParamCollection
{
get
{
return (AnimalCollect)base[s_property];
}
} }
/// <summary>
/// 自定义一个集合
/// </summary>
[ConfigurationCollection(typeof(Animal))]
public class AnimalCollect : ConfigurationElementCollection
{
// 基本上,所有的方法都只要简单地调用基类的实现就可以了。
public AnimalCollect()
: base(StringComparer.OrdinalIgnoreCase) // 忽略大小写
{ }
// 其实关键就是这个索引器。但它也是调用基类的实现,只是做下类型转就行了。
new public Animal this[string cname]
{
get
{
return (Animal)base.BaseGet(cname);
}
}
// 下面二个方法中抽象类中必须要实现的。
protected override ConfigurationElement CreateNewElement()
{
return new Animal();
} protected override object GetElementKey(ConfigurationElement element)
{
return ((Animal)element).CName;
}
} /// <summary>
/// 集合中的每个元素
/// </summary>
public class Animal : ConfigurationElement
{
[ConfigurationProperty("cname", IsRequired = true)]
public string CName
{
get
{
return this["cname"].ToString();
}
set
{
this["cname"] = value;
}
} [ConfigurationProperty("ename", IsRequired = true)]
public string EName
{
get
{
return this["ename"].ToString();
}
set
{
this["ename"] = value;
}
}
}

使用:

 var custSection = ConfigurationManager.GetSection("AnimalSection") as AnimalSection;
var s = (from kv in custSection.ParamCollection.Cast<Animal>() select kv).ToList();
string str = string.Empty;
foreach (Animal item in s)
{
str += "中文名:" + item.CName + ",英文名:" + item.EName;
}

(4)配置节点下的多集合节点(键值类型)

 <configuration>
<configSections>
<!--这里name的名字 必须与创建的类的名字相同-->
<section name="AnimalSection" requirePermission="false" type="ConfigNode.AnimalSection,ConfigNode"/>
</configSections> <system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<!--这里的也是-->
<AnimalSection>
<fly>
<add name="燕子" value="swallow" />
<add name="天鹅" value="swan" />
</fly>
<fish>
<add name="鲨鱼" value="shark"/>
<add name="金鱼" value="goldfish"/>
</fish>
<mammalia>
<add name="小狗" value="dog" />
<add name="小猫" value="cat" />
<add name="小兔" value="rabbit" />
</mammalia>
</AnimalSection>
</configuration>

AnimalSection类:

  // 所有配置节点都要选择这个基类  ConfigurationSection
public class AnimalSection : ConfigurationSection
{
[ConfigurationProperty("mammalia", IsDefaultCollection = false)]
public NameValueConfigurationCollection Mammalia
{
get
{
return (NameValueConfigurationCollection)base["mammalia"];
}
set
{
base["mammalia"] = value;
}
} [ConfigurationProperty("fly", IsDefaultCollection = false)]
public NameValueConfigurationCollection Fly
{
get
{
return (NameValueConfigurationCollection)base["fly"];
}
set
{
base["fly"] = value;
}
} [ConfigurationProperty("fish", IsDefaultCollection = false)]
public NameValueConfigurationCollection Fish
{
get
{
return (NameValueConfigurationCollection)base["fish"];
}
set
{
base["fish"] = value;
}
} }

使用:

  AnimalSection animal = ConfigurationManager.GetSection("AnimalSection") as AnimalSection;
string str = string.Empty;
foreach (string key in animal.Mammalia.AllKeys)
{
str += "中文名:" + key + ",英文名:" + animal.Mammalia[key].Value;
}

(5)配置节点下的多集合节点(自定义类型)

 <configuration>
<configSections>
<!--这里name的名字 必须与创建的类的名字相同-->
<section name="FamilySection" requirePermission="false" type="ConfigNode.FamilySection,ConfigNode"/>
</configSections> <system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<FamilySection number="">
<myself name="Z" age="" sex="男" />
<familyMember>
<add name="ZR" age="" sex="男" relation="父子" />
<add name="WY" age="" sex="女" relation="母子" />
<add name="ZZ" age="" sex="男" relation="兄弟" />
<add name="ZG" age="" sex="女" relation="兄妹" />
<remove name="ZG" />
</familyMember>
</FamilySection>
</configuration>

FamilySection类:

 using System.Configuration;
public class FamilySection : ConfigurationSection
{
/// <summary>
/// 获取父节点自定义配置的值
/// </summary>
[ConfigurationProperty("number", IsRequired = true)]
public int Number
{
get
{
return (int)base["number"];
}
set
{
base["number"] = value;
}
}
[ConfigurationProperty("myself", IsDefaultCollection = false)]
public MySelfSection MySelf
{
get
{
return (MySelfSection)base["myself"];
}
set
{
base["myself"] = value;
}
} [ConfigurationProperty("familyMember", IsRequired = false)]
[ConfigurationCollection(typeof(FamilyMemberSection), CollectionType = ConfigurationElementCollectionType.AddRemoveClearMap, RemoveItemName = "remove")]
public FamilyMember FamilyMember
{
get
{
return (FamilyMember)base["familyMember"];
}
set
{
base["familyMember"] = value;
}
}
} public class MySelfSection : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true, IsKey = true)]
public string Name
{
get { return (string)base["name"]; }
set { base["name"] = value; }
}
[ConfigurationProperty("age", IsRequired = true)]
public int Age
{
get { return (int)base["age"]; }
set { base["age"] = value; }
}
[ConfigurationProperty("sex", IsRequired = true)]
public string Sex
{
get { return (string)base["sex"]; }
set { base["sex"] = value; }
}
}
public class FamilyMemberSection : MySelfSection
{
[ConfigurationProperty("relation", IsRequired = true)]
public string Relation
{
get { return (string)base["relation"]; }
set { base["relation"] = value; }
}
} public class FamilyMember : ConfigurationElementCollection
{ protected override ConfigurationElement CreateNewElement()
{
return new FamilyMemberSection();
} protected override object GetElementKey(ConfigurationElement element)
{
return ((FamilyMemberSection)element).Name;
} public FamilyMemberSection this[int i]
{
get
{
return (FamilyMemberSection)base.BaseGet(i);
}
} public FamilyMemberSection this[string key]
{
get
{
return (FamilyMemberSection)base.BaseGet(key);
}
}
}

使用:

  FamilySection family = ConfigurationManager.GetSection("FamilySection") as FamilySection;
string number = family.Number.ToString();
string myself = family.MySelf.Name + "-" + family.MySelf.Age + "-" + family.MySelf.Sex;
string str = string.Empty;
foreach (FamilyMemberSection item in family.FamilyMember)
{
str += item.Name + "-" + item.Age + "-" + item.Sex + "-" + item.Relation;
}

(6)对配置多个section分组

 <configuration>
<configSections>
<!--这里name的名字 必须与创建的类的名字相同--> <sectionGroup type="ConfigNode.TestSectionGroup,ConfigNode" name="textgroup">
<section name="score" type="ConfigNode.ScoreSection,ConfigNode" allowDefinition="Everywhere"/>
<section name="project" type="ConfigNode.ProjectSection,ConfigNode" allowDefinition="Everywhere"/>
</sectionGroup>
</configSections> <system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<textgroup>
<score chinese=""></score>
<project name="测试"></project>
</textgroup>

需要单独配置Group的类:

  public class TestSectionGroup : ConfigurationSectionGroup
{
public ProjectSection Project
{
get
{
return (ProjectSection)base.Sections["project"];
} } public ScoreSection Score
{
get
{
return (ScoreSection)base.Sections["score"];
}
}
}

使用:

 //在exe中使用  TestSectionGroup group = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).SectionGroups["textgroup"];
//在web程序中使用:续引用System.Web.Configuration;
TestSectionGroup group = (TestSectionGroup)WebConfigurationManager.OpenWebConfiguration("~").SectionGroups["textgroup"]; string name = group.Project.Name;