Подтвердить что ты не робот

Пользовательский раздел конфигурации в App.config С#


Я новичок с разделами конфигурации в С#
Я хочу создать пользовательский раздел в файле конфигурации. То, что я пробовал после googling, выглядит следующим образом
Файл конфигурации:

    <?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");


Что мне не хватает?
Спасибо.

Edit
В конечном итоге мне нужно

    <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>
4b9b3361

Ответ 1

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>

Применение:

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 />");
 }
}

Ответ 2

Попробуйте использовать:

var cf = (CustomSection)System.Configuration.ConfigurationManager.GetSection("MyCustomSections/CustomSection");

Вам потребуется имя группы разделов и пользовательский раздел.

Ответ 3

Выделите ConfigurationSection нажмите F1, Вы увидите, что реализация на веб-сайте MSDN переопределяет свойство "Свойства", которое возвращает "ConfigurationPropertyCollection", так как ваши свойства имеют соответствующий атрибут этого типа, вы должны иметь возможность заполнять эту коллекцию своими свойствами, если не обернуть их так же, как у парней MS.