Ler em inglês

Compartilhar via


ConfigurationSectionCollection Classe

Definição

Representa uma coleção das seções relacionadas dentro de um arquivo de configuração.

C#
public sealed class ConfigurationSectionCollection : System.Collections.Specialized.NameObjectCollectionBase
C#
[System.Serializable]
public sealed class ConfigurationSectionCollection : System.Collections.Specialized.NameObjectCollectionBase
Herança
ConfigurationSectionCollection
Atributos

Exemplos

O exemplo de código a seguir mostra como usar a ConfigurationSectionCollection classe .

C#
using System;
using System.Configuration;
using System.Collections;

namespace Samples.AspNet.Configuration
{

    // Define a custom section programmatically.
    public sealed class CustomSection :
        ConfigurationSection
    {
        // The collection (property bag) that contains 
        // the section properties.
        private static ConfigurationPropertyCollection _Properties;

        // The FileName property.
        private static readonly ConfigurationProperty _FileName =
            new ConfigurationProperty("fileName",
            typeof(string), "default.txt",
            ConfigurationPropertyOptions.IsRequired);

        // The MasUsers property.
        private static readonly ConfigurationProperty _MaxUsers =
            new ConfigurationProperty("maxUsers",
            typeof(long), (long)1000,
            ConfigurationPropertyOptions.None);

        // The MaxIdleTime property.
        private static readonly ConfigurationProperty _MaxIdleTime =
            new ConfigurationProperty("maxIdleTime",
            typeof(TimeSpan), TimeSpan.FromMinutes(5),
            ConfigurationPropertyOptions.IsRequired);

        // CustomSection constructor.
        public CustomSection()
        {
            // Property initialization
            _Properties =
                new ConfigurationPropertyCollection();

            _Properties.Add(_FileName);
            _Properties.Add(_MaxUsers);
            _Properties.Add(_MaxIdleTime);
        }

        // This is a key customization. 
        // It returns the initialized property bag.
        protected override ConfigurationPropertyCollection Properties
        {
            get
            {
                return _Properties;
            }
        }

        [StringValidator(InvalidCharacters = " ~!@#$%^&*()[]{}/;'\"|\\",
            MinLength = 1, MaxLength = 60)]
        public string FileName
        {
            get
            {
                return (string)this["fileName"];
            }
            set
            {

                this["fileName"] = value;
            }
        }

        [LongValidator(MinValue = 1, MaxValue = 1000000,
            ExcludeRange = false)]
        public long MaxUsers
        {
            get
            {
                return (long)this["maxUsers"];
            }
            set
            {
                this["maxUsers"] = value;
            }
        }

        [TimeSpanValidator(MinValueString = "0:0:30",
            MaxValueString = "5:00:0",
            ExcludeRange = false)]
        public TimeSpan MaxIdleTime
        {
            get
            {
                return (TimeSpan)this["maxIdleTime"];
            }
            set
            {
                this["maxIdleTime"] = value;
            }
        }
    }

    class UsingCustomSectionCollection
    {

        // Create a custom section.
        static void CreateSection()
        {
            try
            {

                CustomSection customSection;

                // Get the current configuration file.
                System.Configuration.Configuration config =
                        ConfigurationManager.OpenExeConfiguration(
                        ConfigurationUserLevel.None);

                // Create the section entry  
                // in the <configSections> and the 
                // related target section in <configuration>.
                if (config.Sections["CustomSection"] == null)
                {
                    customSection = new CustomSection();
                    config.Sections.Add("CustomSection", customSection);
                    customSection.SectionInformation.ForceSave = true;
                    config.Save(ConfigurationSaveMode.Full);
                }
            }
            catch (ConfigurationErrorsException err)
            {
                Console.WriteLine(err.ToString());
            }
        }

        static void GetAllKeys()
        {

            try
            {
                System.Configuration.Configuration config =
                ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None);

                ConfigurationSectionCollection sections =
                    config.Sections;

                foreach (string key in sections.Keys)
                {
                    Console.WriteLine(
                     "Key value: {0}", key);
                }
            }
            catch (ConfigurationErrorsException err)
            {
                Console.WriteLine(err.ToString());
            }
        }


        static void Clear()
        {

            try
            {
                System.Configuration.Configuration config =
                ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None);

                config.Sections.Clear();

                config.Save(ConfigurationSaveMode.Full);
            }
            catch (ConfigurationErrorsException err)
            {
                Console.WriteLine(err.ToString());
            }
        }


        static void GetSection()
        {

            try
            {
                CustomSection customSection =
                    ConfigurationManager.GetSection(
                    "CustomSection") as CustomSection;

                if (customSection == null)
                    Console.WriteLine(
                        "Failed to load CustomSection.");
                else
                {
                    // Display section information
                    Console.WriteLine("Defaults:");
                    Console.WriteLine("File Name:       {0}",
                        customSection.FileName);
                    Console.WriteLine("Max Users:       {0}",
                        customSection.MaxUsers);
                    Console.WriteLine("Max Idle Time:   {0}",
                        customSection.MaxIdleTime);
                }
            }
            catch (ConfigurationErrorsException err)
            {
                Console.WriteLine(err.ToString());
            }
        }

        static void GetEnumerator()
        {

            try
            {
                System.Configuration.Configuration config =
                ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None);

                ConfigurationSectionCollection sections =
                    config.Sections;

                IEnumerator secEnum =
                    sections.GetEnumerator();

                int i = 0;
                while (secEnum.MoveNext())
                {
                    string setionName = sections.GetKey(i);
                    Console.WriteLine(
                        "Section name: {0}", setionName);
                    i += 1;
                }
            }
            catch (ConfigurationErrorsException err)
            {
                Console.WriteLine(err.ToString());
            }
        }

        static void GetKeys()
        {

            try
            {
                System.Configuration.Configuration config =
                ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None);

                ConfigurationSectionCollection sections =
                    config.Sections;

                foreach (string key in sections.Keys)
                {

                    Console.WriteLine(
                     "Key value: {0}", key);
                }
            }
            catch (ConfigurationErrorsException err)
            {
                Console.WriteLine(err.ToString());
            }
        }


        static void GetItems()
        {

            try
            {
                System.Configuration.Configuration config =
                ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None);

                ConfigurationSectionCollection sections =
                    config.Sections;

                ConfigurationSection section1 =
                    sections["runtime"];

                ConfigurationSection section2 =
                    sections[0];

                Console.WriteLine(
                     "Section1: {0}", section1.SectionInformation.Name);

                Console.WriteLine(
                    "Section2: {0}", section2.SectionInformation.Name);
            }
            catch (ConfigurationErrorsException err)
            {
                Console.WriteLine(err.ToString());
            }
        }


        static void Remove()
        {

            try
            {
                System.Configuration.Configuration config =
                ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None);

                CustomSection customSection =
                    config.GetSection(
                    "CustomSection") as CustomSection;

                if (customSection != null)
                {
                    config.Sections.Remove("CustomSection");
                    customSection.SectionInformation.ForceSave = true;
                    config.Save(ConfigurationSaveMode.Full);
                }
                else
                    Console.WriteLine(
                        "CustomSection does not exists.");
            }
            catch (ConfigurationErrorsException err)
            {
                Console.WriteLine(err.ToString());
            }
        }

        static void AddSection()
        {

            try
            {
                System.Configuration.Configuration config =
                ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None);

                CustomSection customSection =
                    new CustomSection();

                string index =
                    config.Sections.Count.ToString();

                customSection.FileName =
                    "newFile" + index + ".txt";

                string sectionName = "CustomSection" + index;

                TimeSpan ts = new TimeSpan(0, 15, 0);
                customSection.MaxIdleTime = ts;
                customSection.MaxUsers = 100;

                config.Sections.Add(sectionName, customSection);
                customSection.SectionInformation.ForceSave = true;
                config.Save(ConfigurationSaveMode.Full);
            }
            catch (ConfigurationErrorsException err)
            {
                Console.WriteLine(err.ToString());
            }
        }

        // Exercise the collection.
        // Uncomment the function you want to exercise.
        // Start with CreateSection().
        static void Main(string[] args)
        {
            CreateSection();
            // AddSection();
            // GetSection();
            // GetEnumerator();
            // GetAllKeys();
            // GetKeys();
            // GetItems();

            // Remove();
            // Clear();
        }
    }
}

O exemplo a seguir é um trecho do arquivo de configuração usado pelo exemplo anterior.

XML
<?xml version="1.0" encoding="utf-8"?>  
<configuration>  
  <configSections>  

    <section name="CustomSection"   
      type="Samples.AspNet.Configuration.CustomSection, ConfigurationSectionCollection, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" allowDefinition="Everywhere" allowExeDefinition="MachineToApplication" restartOnExternalChanges="true" />  

  </configSections>  

  <CustomSection fileName="default.txt" maxUsers="1000"   
    maxIdleTime="00:05:00" />  

</configuration>  

Comentários

Use a ConfigurationSectionCollection classe para iterar por meio de uma coleção de ConfigurationSection objetos . Você pode acessar essa coleção de objetos usando a Sections propriedade ou a Sections propriedade .

A ConfigurationSectionCollection classe também é usada na criação de tipos personalizados que estendem a ConfigurationSection classe .

Propriedades

Count

Obtém o número de seções neste objeto ConfigurationSectionCollection.

Count

Obtém o número de pares chave-valor contidos na instância NameObjectCollectionBase.

(Herdado de NameObjectCollectionBase)
IsReadOnly

Obtém ou define um valor que indica se a instância de NameObjectCollectionBase é somente leitura.

(Herdado de NameObjectCollectionBase)
Item[Int32]

Obtém o objeto ConfigurationSection especificado.

Item[String]

Obtém o objeto ConfigurationSection especificado.

Keys

Obtém as chaves para todos os objetos ConfigurationSection contidos nesse objeto ConfigurationSectionCollection.

Keys

Obtém uma instância de NameObjectCollectionBase.KeysCollection que contém todas as chaves da instância de NameObjectCollectionBase.

(Herdado de NameObjectCollectionBase)

Métodos

Add(String, ConfigurationSection)

Adiciona um objeto ConfigurationSection ao objeto ConfigurationSectionCollection.

BaseAdd(String, Object)

Adiciona uma entrada com a chave e o valor especificados à instância NameObjectCollectionBase.

(Herdado de NameObjectCollectionBase)
BaseClear()

Remove todas as entradas da instância NameObjectCollectionBase.

(Herdado de NameObjectCollectionBase)
BaseGet(Int32)

Obtém o valor da entrada no índice especificado da instância NameObjectCollectionBase.

(Herdado de NameObjectCollectionBase)
BaseGet(String)

Obtém o valor da primeira entrada com a chave especificada da instância de NameObjectCollectionBase.

(Herdado de NameObjectCollectionBase)
BaseGetAllKeys()

Retorna uma matriz String que contém todas as chaves na instância NameObjectCollectionBase.

(Herdado de NameObjectCollectionBase)
BaseGetAllValues()

Retorna uma matriz Object que contém todos os valores na instância NameObjectCollectionBase.

(Herdado de NameObjectCollectionBase)
BaseGetAllValues(Type)

Retorna uma matriz do tipo especificado que contém todos os valores na instância NameObjectCollectionBase.

(Herdado de NameObjectCollectionBase)
BaseGetKey(Int32)

Obtém a chave da entrada no índice especificado da instância NameObjectCollectionBase.

(Herdado de NameObjectCollectionBase)
BaseHasKeys()

Obtém um valor que indica se a instância NameObjectCollectionBase contém entradas cujas chaves não são null.

(Herdado de NameObjectCollectionBase)
BaseRemove(String)

Remove as entradas com a chave especificada da instância de NameObjectCollectionBase.

(Herdado de NameObjectCollectionBase)
BaseRemoveAt(Int32)

Remove a entrada no índice especificado da instância NameObjectCollectionBase.

(Herdado de NameObjectCollectionBase)
BaseSet(Int32, Object)

Define o valor da entrada no índice especificado da instância NameObjectCollectionBase.

(Herdado de NameObjectCollectionBase)
BaseSet(String, Object)

Define o valor da primeira entrada com a chave especificada na instância NameObjectCollectionBase, se encontrada; caso contrário, adiciona uma entrada com a chave especificada e o valor para a instância NameObjectCollectionBase.

(Herdado de NameObjectCollectionBase)
Clear()

Limpa esse objeto ConfigurationSectionCollection.

CopyTo(ConfigurationSection[], Int32)

Copia esse objeto ConfigurationSectionCollection para uma matriz.

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
Get(Int32)

Obtém o objeto ConfigurationSection especificado contido nesse objeto ConfigurationSectionCollection.

Get(String)

Obtém o objeto ConfigurationSection especificado contido nesse objeto ConfigurationSectionCollection.

GetEnumerator()

Obtém um enumerador que pode iterar por meio desse objeto ConfigurationSectionCollection.

GetHashCode()

Serve como a função de hash padrão.

(Herdado de Object)
GetKey(Int32)

Obtém a chave do objeto ConfigurationSection especificado contido neste objeto ConfigurationSectionCollection.

GetObjectData(SerializationInfo, StreamingContext)
Obsoleto.

Usado pelo sistema durante a serialização.

GetObjectData(SerializationInfo, StreamingContext)
Obsoleto.

Implementa a interface ISerializable e retorna os dados necessários para serializar a instância NameObjectCollectionBase.

(Herdado de NameObjectCollectionBase)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
MemberwiseClone()

Cria uma cópia superficial do Object atual.

(Herdado de Object)
OnDeserialization(Object)

Implementa a interface ISerializable e gera o evento de desserialização quando a desserialização for concluída.

(Herdado de NameObjectCollectionBase)
Remove(String)

Remove o objeto ConfigurationSection especificado desse objeto ConfigurationSectionCollection.

RemoveAt(Int32)

Remove o objeto ConfigurationSection especificado desse objeto ConfigurationSectionCollection.

ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.

(Herdado de Object)

Implantações explícitas de interface

ICollection.CopyTo(Array, Int32)

Copia todo o NameObjectCollectionBase em um Array unidimensional compatível, começando no índice especificado da matriz de destino.

(Herdado de NameObjectCollectionBase)
ICollection.IsSynchronized

Obtém um valor que indica se o acesso ao objeto NameObjectCollectionBase é sincronizado (thread-safe).

(Herdado de NameObjectCollectionBase)
ICollection.SyncRoot

Obtém um objeto que pode ser usado para sincronizar o acesso ao objeto NameObjectCollectionBase.

(Herdado de NameObjectCollectionBase)

Métodos de Extensão

Cast<TResult>(IEnumerable)

Converte os elementos de um IEnumerable para o tipo especificado.

OfType<TResult>(IEnumerable)

Filtra os elementos de um IEnumerable com base em um tipo especificado.

AsParallel(IEnumerable)

Habilita a paralelização de uma consulta.

AsQueryable(IEnumerable)

Converte um IEnumerable em um IQueryable.

Aplica-se a

Produto Versões
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9

Confira também