C# 自定义配置文件
先来一段代码,创建了一个名为TestSection的节点
namespace _51Take.Testing
{
public class TestSection : ConfigurationSection
{
private static ConfigurationProperty s_property = new ConfigurationProperty(string.Empty, typeof(TestCollection), null, ConfigurationPropertyOptions.IsDefaultCollection);
[ConfigurationProperty("", Options = ConfigurationPropertyOptions.IsDefaultCollection)]
public TestCollection TestCollections
{
get { return (TestCollection)base[s_property]; }
}
}
[ConfigurationCollection(typeof(TestConfig))]
public class TestCollection : ConfigurationElementCollection
{
public TestCollection() : base(StringComparer.OrdinalIgnoreCase) { }
new public TestConfig this[string name]
{
get { return (TestConfig)base.BaseGet(name); }
set { base[name] = value; }
}
protected override ConfigurationElement CreateNewElement()
{
return new TestConfig();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((TestConfig)element).Name;
}
}
// 这里是节点里面的属性,随意添加
public class TestConfig : 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; }
}
}
上面的代码其实百度上都差不多,但是最重要的没说
运行下去你会发现报错
解决这个问题你需要在配置文件添加这一段,name是节点名,type内容,逗号前是节点类的命名空间加上类名,逗号后是节点类所在类库的类库名
然后读
var config = ConfigurationManager.GetSection("TestSection") as TestSection;
TestConfig pt = config.TestCollections.Cast<TestConfig>().FirstOrDefault();