ConfigurationSectionGroup Classe

Definição

Representa um grupo de seções relacionadas dentro de um arquivo de configuração.Represents a group of related sections within a configuration file.

public ref class ConfigurationSectionGroup
public class ConfigurationSectionGroup
type ConfigurationSectionGroup = class
Public Class ConfigurationSectionGroup
Herança
ConfigurationSectionGroup
Derivado

Exemplos

O exemplo a seguir mostra como usar a classe ConfigurationSectionGroup para recuperar as definições de configuração.The following example shows how to use the ConfigurationSectionGroup class to retrieve configuration settings. O exemplo é um aplicativo de console que lê as definições de configuração e grava informações sobre cada grupo de seções de configuração e as seções contidas nele no console.The example is a console application that reads configuration settings and writes information about each configuration section group and the sections in it to the console.

O método Main carrega as definições de configuração em um objeto Configuration, recupera a coleção SectionGroups do objeto Configuration e, em seguida, chama o método ShowSectionGroupCollectionInfo para exibir os valores de propriedade da seção.The Main method loads the configuration settings into a Configuration object, retrieves the SectionGroups collection from the Configuration object, and then calls the ShowSectionGroupCollectionInfo method to display the section property values.

O método ShowSectionGroupCollectionInfo itera através dos grupos de seções e chama o método ShowSectionGroupInfo para cada um.The ShowSectionGroupCollectionInfo method iterates through the section groups and calls the ShowSectionGroupInfo method for each one.

O método ShowSectionGroupInfo exibe o nome do grupo de seções, alguns valores de propriedade e os nomes das seções que ele contém.The ShowSectionGroupInfo method displays the name of the section group, some property values, and the names of the sections that it contains. Se o grupo de seções contiver grupos de seções, esse método chamará ShowSectionGroupCollectionInfo recursivamente para exibir esses grupos de seções.If the section group contains section groups, this method calls ShowSectionGroupCollectionInfo recursively to display those section groups.

O campo indentLevel é usado para adicionar espaços ao lado esquerdo das linhas exibidas para mostrar agrupamentos lógicos.The indentLevel field is used to add spaces to the left side of displayed lines to show logical groupings. Todas as linhas são limitadas a 79 caracteres de texto para evitar quebra automática de linha, o que dificultaria a distinção dos agrupamentos lógicos.All lines are limited to 79 characters of text to avoid line wrapping, which would make it harder to distinguish the logical groupings.

using System;
using System.Collections;
using System.Configuration;

namespace Samples.AspNet
{
    class UsingConfigurationSectionGroup
    {
        static int indentLevel = 0;

        static void Main(string[] args)
        {

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

            // Get the collection of the section groups.
            ConfigurationSectionGroupCollection sectionGroups =
                config.SectionGroups;

            // Display the section groups.
            ShowSectionGroupCollectionInfo(sectionGroups);
        }

        static void ShowSectionGroupCollectionInfo(
            ConfigurationSectionGroupCollection sectionGroups)
        {
            foreach (ConfigurationSectionGroup sectionGroup in sectionGroups)
            {
                ShowSectionGroupInfo(sectionGroup);
            }
        }

        static void ShowSectionGroupInfo(
            ConfigurationSectionGroup sectionGroup)
        {
            // Get the section group name.
            indent("Section Group Name: " + sectionGroup.Name);

            // Get the fully qualified group name.
            indent("Section Group Name: " + sectionGroup.SectionGroupName);

            indentLevel++;

            indent("Type: " + sectionGroup.Type);
            indent("Is Group Required?: " + 
                sectionGroup.IsDeclarationRequired);
            indent("Is Group Declared?: " + sectionGroup.IsDeclared);
            indent("Contained Sections:");

            indentLevel++;
            foreach (ConfigurationSection section 
                in sectionGroup.Sections)
            {
                indent("Section Name:" + section.SectionInformation.Name);
            }
            indentLevel--;

            // Display contained section groups if there are any.
            if (sectionGroup.SectionGroups.Count > 0)
            {
                indent("Contained Section Groups:");

                indentLevel++;
                ConfigurationSectionGroupCollection sectionGroups =
                    sectionGroup.SectionGroups;
                ShowSectionGroupCollectionInfo(sectionGroups);
            }

            Console.WriteLine("");
            indentLevel--;
        }

        static void indent(string text)
        {
            for (int i = 0; i < indentLevel; i++)
            {
                Console.Write("  ");
            }
            Console.WriteLine(text.Substring(0, Math.Min(79 - indentLevel * 2, text.Length)));
        }
    }
}
Imports System.Collections
Imports System.Configuration

Class UsingConfigurationSectionGroup
   Private Shared indentLevel As Integer = 0
    
    Public Shared Sub Main(ByVal args() As String)

        ' Get the application configuration file.
        Dim config As System.Configuration.Configuration = _
            ConfigurationManager.OpenExeConfiguration( _
            ConfigurationUserLevel.None)

        ' Get the collection of the section groups.
        Dim sectionGroups As ConfigurationSectionGroupCollection = _
            config.SectionGroups

        ' Display the section groups.
        ShowSectionGroupCollectionInfo(sectionGroups)
    End Sub

    Shared Sub ShowSectionGroupCollectionInfo( _
        ByVal sectionGroups _
        As ConfigurationSectionGroupCollection)

        Dim group As ConfigurationSectionGroup
        For Each group In sectionGroups
            ShowSectionGroupInfo(group)
        Next group
    End Sub

    Shared Sub ShowSectionGroupInfo( _
    ByVal sectionGroup As ConfigurationSectionGroup)
        ' Get the section group name.
        indent("Section Group Name: " + sectionGroup.Name)

        ' Get the fully qualified section group name.
        indent("Section Group Name: " + sectionGroup.SectionGroupName)

        indentLevel += 1

        indent("Type: " + sectionGroup.Type)
        indent("Is Group Required?: " + _
           sectionGroup.IsDeclarationRequired.ToString())
        indent("Is Group Declared?: " + _
            sectionGroup.IsDeclared.ToString())
        indent("Contained Sections:")

        indentLevel += 1
        Dim section As ConfigurationSection
        For Each section In sectionGroup.Sections
            indent("Section Name:" + section.SectionInformation.Name)
        Next section
        indentLevel -= 1

        If (sectionGroup.SectionGroups.Count > 0) Then
            indent("Contained Section Groups:")

            indentLevel += 1
            Dim sectionGroups As ConfigurationSectionGroupCollection = _
                sectionGroup.SectionGroups
            ShowSectionGroupCollectionInfo(sectionGroups)
            indentLevel -= 1
        End If

        indent("")
        indentLevel -= 1

    End Sub
    Shared Sub indent(ByVal text As String)
        Dim i As Integer
        For i = 0 To indentLevel - 1
            Console.Write("  ")
        Next i
        Console.WriteLine(Left(text, 79 - indentLevel * 2))
    End Sub

End Class

Comentários

As configurações nos arquivos de configuração (como o arquivo Web. config) são organizadas em seções.Settings in configuration files (such as the Web.config file) are organized into sections. Como algumas seções estão relacionadas, muitas vezes é conveniente agrupá-las em um grupo de seções.Because some sections are related, it is often convenient to group them in a section group. A classe ConfigurationSectionGroup representa o elemento XML sectionGroup usado para agrupar seções quando elas são definidas no elemento configSections de um arquivo de configuração.The ConfigurationSectionGroup class represents the sectionGroup XML element that is used to group sections when they are defined in the configSections element of a configuration file. Os grupos de seções podem ser aninhados (um grupo de seções pode conter outros grupos de seções, bem como seções).Section groups can be nested (a section group can contain other section groups as well as sections). O exemplo a seguir mostra um elemento configSections que define três grupos de seções aninhados:The following example shows a configSections element that defines three nested section groups:

<configSections>  
  <sectionGroup name="system.web.extensions"...>  
    <sectionGroup name="scripting" ...>  
      <section name="scriptResourceHandler".../>  
      <sectionGroup name="webServices"...>  
        <section name="jsonSerialization" .../>  
        <section name="profileService" ... />        <section name="authenticationService" .../>  
        <section name="roleService" .../>  
      </sectionGroup>  
    </sectionGroup>  
  </sectionGroup>  
</configSections>  

O sistema de configuração carrega as configurações de arquivos de configuração em objetos ConfigurationSectionGroup.The configuration system loads settings from configuration files into ConfigurationSectionGroup objects. Você pode usar as propriedades Sections e SectionGroups para acessar as seções e os grupos de seções contidos em um objeto ConfigurationSectionGroup.You can use the Sections and SectionGroups properties to access the sections and section groups that are contained in a ConfigurationSectionGroup object.

Para obter mais informações sobre como acessar informações de arquivos de configuração, consulte a classe ConfigurationManager.For more information about how to access information from configuration files, see the ConfigurationManager class.

Construtores

ConfigurationSectionGroup()

Inicializa uma nova instância da classe ConfigurationSectionGroup.Initializes a new instance of the ConfigurationSectionGroup class.

Propriedades

IsDeclarationRequired

Obtém um valor que indica se a declaração desse objeto ConfigurationSectionGroup é necessária.Gets a value that indicates whether this ConfigurationSectionGroup object declaration is required.

IsDeclared

Obtém um valor que indica se esse objeto ConfigurationSectionGroup é declarado.Gets a value that indicates whether this ConfigurationSectionGroup object is declared.

Name

Obtém a propriedade de nome deste objeto ConfigurationSectionGroup.Gets the name property of this ConfigurationSectionGroup object.

SectionGroupName

Obtém o nome do grupo da seção associado a esta ConfigurationSectionGroup.Gets the section group name associated with this ConfigurationSectionGroup.

SectionGroups

Obtém um objeto ConfigurationSectionGroupCollection que contém todos os objetos ConfigurationSectionGroup que são filhos deste objeto ConfigurationSectionGroup.Gets a ConfigurationSectionGroupCollection object that contains all the ConfigurationSectionGroup objects that are children of this ConfigurationSectionGroup object.

Sections

Obtém um objeto ConfigurationSectionCollection que contém todos os objetos ConfigurationSection dentro desse objeto ConfigurationSectionGroup.Gets a ConfigurationSectionCollection object that contains all of ConfigurationSection objects within this ConfigurationSectionGroup object.

Type

Obtém ou define o tipo ConfigurationSectionGroup para esse objeto.Gets or sets the type for this ConfigurationSectionGroup object.

Métodos

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object.

(Herdado de Object)
ForceDeclaration()

Força a declaração para este objeto ConfigurationSectionGroup.Forces the declaration for this ConfigurationSectionGroup object.

ForceDeclaration(Boolean)

Força a declaração para este objeto ConfigurationSectionGroup.Forces the declaration for this ConfigurationSectionGroup object.

GetHashCode()

Serve como a função de hash padrão.Serves as the default hash function.

(Herdado de Object)
GetType()

Obtém o Type da instância atual.Gets the Type of the current instance.

(Herdado de Object)
MemberwiseClone()

Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object.

(Herdado de Object)
ShouldSerializeSectionGroupInTargetVersion(FrameworkName)

Indica se a instância ConfigurationSectionGroup atual deve ser serializada quando a hierarquia de objetos de configuração é serializada para a versão de destino especificada do .NET Framework.NET Framework.Indicates whether the current ConfigurationSectionGroup instance should be serialized when the configuration object hierarchy is serialized for the specified target version of the .NET Framework.NET Framework.

ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object.

(Herdado de Object)

Aplica-se a

Veja também