App.config中的自定义配置部分C#

Cha*_*ish 16 c# configuration custom-configuration


我是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>
Run Code Online (Sandbox Code Playgroud)


CustomSection.cs

    namespace CustomSectionTest
{
    public class CustomSection : ConfigurationSection
    {
        [ConfigurationProperty("key", DefaultValue="Default", IsRequired = true)]
        [StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 60)]
        public String Key
        {
            get { return this["key"].ToString(); }
            set { this["key"] = value; }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


当我使用此代码检索Section时,我收到一条错误说配置错误.

var cf = (CustomSection)System.Configuration.ConfigurationManager.GetSection("CustomSection");
Run Code Online (Sandbox Code Playgroud)


我错过了什么?
谢谢.

编辑
我最终需要的是什么

    <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>
Run Code Online (Sandbox Code Playgroud)

Nes*_*zon 38

App.config中:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <sectionGroup name="customAppSettingsGroup">
      <section name="customAppSettings" type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    </sectionGroup>
  </configSections>
  <customAppSettingsGroup>
    <customAppSettings>
      <add key="KeyOne" value="ValueOne"/>
      <add key="KeyTwo" value="ValueTwo"/>
    </customAppSettings>
  </customAppSettingsGroup>
</configuration>
Run Code Online (Sandbox Code Playgroud)

用法:

NameValueCollection settings =  
   ConfigurationManager.GetSection("customAppSettingsGroup/customAppSettings")
   as System.Collections.Specialized.NameValueCollection;

if (settings != null)
{
 foreach (string key in settings.AllKeys)
 {
  Response.Write(key + ": " + settings[key] + "<br />");
 }
}
Run Code Online (Sandbox Code Playgroud)

  • 对于任何想要让它快速工作的人.3件事:1.您必须在参考文献中添加对System.Configuration的引用,2.使用System.Configuration; 3.使用System.Collections.Specialized; (14认同)
  • 如果需要,还可以省略组(customAppSettingsGroup). (3认同)