我是一個非常初學的配置部分在c#
我想在配置文件中創建一個自定義部分。我已經在Google上搜尋後嘗試是因爲如下
配置文件:
在App.config中的自定義配置部分C#
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="MyCustomSections">
<section name="CustomSection" type="CustomSectionTest.CustomSection,CustomSection"/>
</sectionGroup>
</configSections>
<MyCustomSections>
<CustomSection key="Default"/>
</MyCustomSections>
</configuration>
CustomSection.cs
namespace CustomSectionTest
{
public class CustomSection : ConfigurationSection
{
[ConfigurationProperty("key", DefaultValue="Default", IsRequired = true)]
[StringValidator(InvalidCharacters = "[email protected]#$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 60)]
public String Key
{
get { return this["key"].ToString(); }
set { this["key"] = value; }
}
}
}
當我使用此代碼檢索第一節得到一個錯誤說配置錯誤。
var cf = (CustomSection)System.Configuration.ConfigurationManager.GetSection("CustomSection");
我缺少什麼?
謝謝。
編輯
我需要的最終是什麼
<CustomConfigSettings>
<Setting id="1">
<add key="Name" value="N"/>
<add key="Type" value="D"/>
</Setting>
<Setting id="2">
<add key="Name" value="O"/>
<add key="Type" value="E"/>
</Setting>
<Setting id="3">
<add key="Name" value="P"/>
<add key="Type" value="F"/>
</Setting>
</CustomConfigSettings>
請查看以下問題:http://stackoverflow.com/questions/3935331/how-to-implement-a-configurationsection-with-a-configurationelementcollection http://stackoverflow.com/questions/7983127/custom- configurationsection http://stackoverflow.com/questions/4738/using-configurationmanager-to-load-config-from-an-arbitrary-location – bytebuster