ConfigurationSectionGroupCollection Classe
Definição
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
Representa uma coleção de objetos ConfigurationSectionGroup .
public ref class ConfigurationSectionGroupCollection sealed : System::Collections::Specialized::NameObjectCollectionBase
public sealed class ConfigurationSectionGroupCollection : System.Collections.Specialized.NameObjectCollectionBase
[System.Serializable]
public sealed class ConfigurationSectionGroupCollection : System.Collections.Specialized.NameObjectCollectionBase
type ConfigurationSectionGroupCollection = class
inherit NameObjectCollectionBase
[<System.Serializable>]
type ConfigurationSectionGroupCollection = class
inherit NameObjectCollectionBase
Public NotInheritable Class ConfigurationSectionGroupCollection
Inherits NameObjectCollectionBase
- Herança
- Atributos
Exemplos
O exemplo de código a seguir mostra como usar a ConfigurationSectionGroupCollection classe .
using System;
using System.Configuration;
using System.Collections;
namespace Samples.Config
{
// Define a custom section.
public sealed class CustomSection :
ConfigurationSection
{
public CustomSection()
{ }
[ConfigurationProperty("fileName", DefaultValue = "default.txt",
IsRequired = true, IsKey = false)]
[StringValidator(InvalidCharacters = " ~!@#$%^&*()[]{}/;'\"|\\",
MinLength = 1, MaxLength = 60)]
public string FileName
{
get
{
return (string)this["fileName"];
}
set
{
this["fileName"] = value;
}
}
[ConfigurationProperty("maxUsers", DefaultValue = (long)10000,
IsRequired = false)]
[LongValidator(MinValue = 1, MaxValue = 10000000,
ExcludeRange = false)]
public long MaxUsers
{
get
{
return (long)this["maxUsers"];
}
set
{
this["maxUsers"] = value;
}
}
[ConfigurationProperty("maxIdleTime",
DefaultValue = "0:10:0",
IsRequired = false)]
[TimeSpanValidator(MinValueString = "0:0:30",
MaxValueString = "5:00:0",
ExcludeRange = false)]
public TimeSpan MaxIdleTime
{
get
{
return (TimeSpan)this["maxIdleTime"];
}
set
{
this["maxIdleTime"] = value;
}
}
}
// Define a custom section group.
public sealed class CustomSectionGroup :
ConfigurationSectionGroup
{
public CustomSectionGroup()
{
}
public CustomSection Custom
{
get { return (CustomSection)
Sections.Get("CustomSection");}
}
}
class UsingCustomSectionGroupCollection
{
// Create a custom section group.
static void CreateSectionGroup()
{
try
{
CustomSectionGroup customSectionGroup;
// Get the current configuration file.
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None);
// Create the section group entry
// in the <configSections> and the
// related target section in <configuration>.
if (config.SectionGroups["CustomGroup"] == null)
{
customSectionGroup = new CustomSectionGroup();
config.SectionGroups.Add("CustomGroup",
customSectionGroup);
customSectionGroup.ForceDeclaration(true);
config.Save(ConfigurationSaveMode.Full);
}
}
catch (ConfigurationErrorsException err)
{
Console.WriteLine(err.ToString());
}
}
// Get the collection group keys i.e.,
// the group names.
//static void GetAllKeys()
//{
// try
// {
// System.Configuration.Configuration config =
// ConfigurationManager.OpenExeConfiguration(
// ConfigurationUserLevel.None);
// ConfigurationSectionGroupCollection groups =
// config.SectionGroups;
// groups.
// foreach (string name in groups.AllKeys)
// {
// Console.WriteLine(
// "Key value: {0}", name);
// }
// }
// catch (ConfigurationErrorsException err)
// {
// Console.WriteLine(err.ToString());
// }
//}
static void Clear()
{
try
{
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None);
config.SectionGroups.Clear();
config.Save(ConfigurationSaveMode.Full);
}
catch (ConfigurationErrorsException err)
{
Console.WriteLine(err.ToString());
}
}
static void GetGroup()
{
try
{
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None);
ConfigurationSectionGroup customGroup =
config.SectionGroups.Get("CustomGroup");
if (customGroup == null)
Console.WriteLine(
"Failed to load CustomSection.");
else
{
// Display section information
Console.WriteLine("Section group name: {0}",
customGroup.SectionGroupName);
Console.WriteLine("Name: {0}",
customGroup.Name);
Console.WriteLine("Type: {0}",
customGroup.Type);
}
}
catch (ConfigurationErrorsException err)
{
Console.WriteLine(err.ToString());
}
}
static void GetEnumerator()
{
try
{
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None);
ConfigurationSectionGroupCollection groups =
config.SectionGroups;
IEnumerator groupEnum =
groups.GetEnumerator();
int i = 0;
while (groupEnum.MoveNext())
{
string groupName = groups.GetKey(i);
Console.WriteLine(
"Group name: {0}", groupName);
i += 1;
}
}
catch (ConfigurationErrorsException err)
{
Console.WriteLine(err.ToString());
}
}
// Get the collection keys i.e., the
// group names.
static void GetKeys()
{
try
{
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None);
ConfigurationSectionGroupCollection groups =
config.SectionGroups;
foreach (string key in groups.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);
ConfigurationSectionGroupCollection groups =
config.SectionGroups;
ConfigurationSectionGroup group1 =
groups.Get("system.net");
ConfigurationSectionGroup group2 =
groups.Get("system.web");
Console.WriteLine(
"Group1: {0}", group1.Name);
Console.WriteLine(
"Group2: {0}", group2.Name);
}
catch (ConfigurationErrorsException err)
{
Console.WriteLine(err.ToString());
}
}
static void Remove()
{
try
{
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None);
ConfigurationSectionGroup customGroup =
config.SectionGroups.Get("CustomGroup");
if (customGroup != null)
{
config.SectionGroups.Remove("CustomGroup");
config.Save(ConfigurationSaveMode.Full);
}
else
Console.WriteLine(
"CustomGroup does not exists.");
}
catch (ConfigurationErrorsException err)
{
Console.WriteLine(err.ToString());
}
}
// Add custom section to the group.
static void AddSection()
{
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>.
ConfigurationSectionGroup customGroup;
customGroup = config.SectionGroups.Get("CustomGroup");
if (customGroup.Sections.Get("CustomSection") == null)
{
customSection = new CustomSection();
customGroup.Sections.Add("CustomSection",
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 CreateSectionGroup().
static void Main(string[] args)
{
CreateSectionGroup();
AddSection();
// GetAllKeys();
// GetGroup();
// GetEnumerator();
// GetKeys();
// GetItems();
// Remove();
// Clear();
}
}
}
Imports System.Configuration
Imports System.Collections
' Define a custom section.
NotInheritable Public Class CustomSection
Inherits ConfigurationSection
Public Sub New()
End Sub
<ConfigurationProperty("fileName", _
DefaultValue:="default.txt", _
IsRequired:=True, _
IsKey:=False), _
StringValidator( _
InvalidCharacters:=" ~!@#$%^&*()[]{}/;'""|\", _
MinLength:=1, _
MaxLength:=60)> _
Public Property FileName() As String
Get
Return CStr(Me("fileName"))
End Get
Set(ByVal value As String)
Me("fileName") = value
End Set
End Property
<ConfigurationProperty("maxUsers", _
DefaultValue:=10000, _
IsRequired:=False), _
LongValidator(MinValue:=1, _
MaxValue:=10000000, _
ExcludeRange:=False)> _
Public Property MaxUsers() As Long
Get
Return Fix(Me("maxUsers"))
End Get
Set(ByVal value As Long)
Me("maxUsers") = value
End Set
End Property
<ConfigurationProperty("maxIdleTime", _
DefaultValue:="0:10:0", _
IsRequired:=False), _
TimeSpanValidator(MinValueString:="0:0:30", _
MaxValueString:="5:00:0", _
ExcludeRange:=False)> _
Public Property MaxIdleTime() As TimeSpan
Get
Return CType(Me("maxIdleTime"), TimeSpan)
End Get
Set(ByVal value As TimeSpan)
Me("maxIdleTime") = value
End Set
End Property
End Class
' Define a custom section group.
NotInheritable Public Class CustomSectionGroup
Inherits ConfigurationSectionGroup
Public Sub New()
End Sub
Public ReadOnly Property Custom() As CustomSection
Get
Return CType(Sections.Get("CustomSection"), _
CustomSection)
End Get
End Property
End Class
Class UsingCustomSectionGroupCollection
' Create a custom section group.
Shared Sub CreateSectionGroup()
Try
Dim customSectionGroup As CustomSectionGroup
' Get the current configuration file.
Dim config As System.Configuration.Configuration = _
ConfigurationManager.OpenExeConfiguration( _
ConfigurationUserLevel.None)
' Create the section group entry
' in the <configSections> and the
' related target section in <configuration>.
If config.SectionGroups("CustomGroup") Is Nothing Then
customSectionGroup = New CustomSectionGroup()
config.SectionGroups.Add("CustomGroup", customSectionGroup)
customSectionGroup.ForceDeclaration(True)
config.Save(ConfigurationSaveMode.Full)
End If
Catch err As ConfigurationErrorsException
Console.WriteLine(err.ToString())
End Try
End Sub
' Get the collection group keys i.e.,
' the group names.
'Shared Sub GetAllKeys()
' Try
' Dim config _
' As System.Configuration.Configuration = _
' ConfigurationManager.OpenExeConfiguration( _
' ConfigurationUserLevel.None)
' Dim groups _
' As ConfigurationSectionGroupCollection = _
' config.SectionGroups
' Dim name As String
' For Each name In groups.AllKeys
' Console.WriteLine("Key value: {0}", name)
' Next name
' Catch err As ConfigurationErrorsException
' Console.WriteLine(err.ToString())
' End Try
'End Sub
Shared Sub Clear()
Try
Dim config _
As System.Configuration.Configuration = _
ConfigurationManager.OpenExeConfiguration( _
ConfigurationUserLevel.None)
config.SectionGroups.Clear()
config.Save(ConfigurationSaveMode.Full)
Catch err As ConfigurationErrorsException
Console.WriteLine(err.ToString())
End Try
End Sub
Shared Sub GetGroup()
Try
Dim config _
As System.Configuration.Configuration = _
ConfigurationManager.OpenExeConfiguration( _
ConfigurationUserLevel.None)
Dim groups _
As ConfigurationSectionGroupCollection = _
config.SectionGroups
Dim customGroup _
As ConfigurationSectionGroup = _
groups.Get("CustomGroup")
If customGroup Is Nothing Then
Console.WriteLine( _
"Failed to load CustomGroup.")
Else
' Display section information
Console.WriteLine("Name: {0}", _
customGroup.Name)
Console.WriteLine("Type: {0}", _
customGroup.Type)
End If
Catch err As ConfigurationErrorsException
Console.WriteLine(err.ToString())
End Try
End Sub
Shared Sub GetEnumerator()
Try
Dim config _
As System.Configuration.Configuration = _
ConfigurationManager.OpenExeConfiguration( _
ConfigurationUserLevel.None)
Dim groups _
As ConfigurationSectionGroupCollection = _
config.SectionGroups
Dim groupEnum As IEnumerator = _
groups.GetEnumerator()
Dim i As Integer = 0
While groupEnum.MoveNext()
Dim groupName As String = groups.GetKey(i)
Console.WriteLine("Group name: {0}", groupName)
i += 1
End While
Catch err As ConfigurationErrorsException
Console.WriteLine(err.ToString())
End Try
End Sub
' Get the collection keys i.e., the
' group names.
Shared Sub GetKeys()
Try
Dim config _
As System.Configuration.Configuration = _
ConfigurationManager.OpenExeConfiguration( _
ConfigurationUserLevel.None)
Dim groups _
As ConfigurationSectionGroupCollection = _
config.SectionGroups
Dim key As String
For Each key In groups.Keys
Console.WriteLine("Key value: {0}", key)
Next key
Catch err As ConfigurationErrorsException
Console.WriteLine(err.ToString())
End Try
End Sub
Shared Sub GetItems()
Try
Dim config _
As System.Configuration.Configuration = _
ConfigurationManager.OpenExeConfiguration( _
ConfigurationUserLevel.None)
Dim groups _
As ConfigurationSectionGroupCollection = _
config.SectionGroups
Dim group1 As ConfigurationSectionGroup = _
groups.Get("system.net")
Dim group2 As ConfigurationSectionGroup = _
groups.Get("system.web")
Console.WriteLine("Group1: {0}", group1.Name)
Console.WriteLine("Group2: {0}", group2.Name)
Catch err As ConfigurationErrorsException
Console.WriteLine(err.ToString())
End Try
End Sub
Shared Sub Remove()
Try
Dim config _
As System.Configuration.Configuration = _
ConfigurationManager.OpenExeConfiguration( _
ConfigurationUserLevel.None)
Dim groups _
As ConfigurationSectionGroupCollection = _
config.SectionGroups
Dim customGroup _
As ConfigurationSectionGroup = groups.Get("CustomGroup")
If Not (customGroup Is Nothing) Then
config.SectionGroups.Remove("CustomGroup")
config.Save(ConfigurationSaveMode.Full)
Else
Console.WriteLine( _
"CustomGroup does not exists.")
End If
Catch err As ConfigurationErrorsException
Console.WriteLine(err.ToString())
End Try
End Sub
' Add custom section to the group.
Shared Sub AddSection()
Try
Dim customSection As CustomSection
' Get the current configuration file.
Dim config _
As System.Configuration.Configuration = _
ConfigurationManager.OpenExeConfiguration( _
ConfigurationUserLevel.None)
Dim groups _
As ConfigurationSectionGroupCollection = _
config.SectionGroups
' Create the section entry
' in the <configSections> and the
' related target section in <configuration>.
Dim customGroup As ConfigurationSectionGroup
customGroup = groups.Get("CustomGroup")
If customGroup.Sections.Get( _
"CustomSection") Is Nothing Then
customSection = New CustomSection()
customGroup.Sections.Add( _
"CustomSection", customSection)
customSection.SectionInformation.ForceSave = True
config.Save(ConfigurationSaveMode.Full)
End If
Catch err As ConfigurationErrorsException
Console.WriteLine(err.ToString())
End Try
End Sub
' Exercise the collection.
' Uncomment the function you want to exercise.
' Start with CreateSectionGroup().
Public Overloads Shared Sub Main(ByVal args() As String)
CreateSectionGroup()
AddSection()
' GetEnumerator();
' GetKeys();
' GetItems();
' Remove();
' Clear();
End Sub
End Class
O exemplo a seguir é um trecho do arquivo de configuração usado pelo exemplo anterior.
<?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 ConfigurationSectionGroupCollection classe para iterar por meio de uma coleção de ConfigurationSectionGroup objetos . Você pode acessar essa coleção de objetos usando a SectionGroups propriedade ou a SectionGroups propriedade .
A ConfigurationSectionGroupCollection classe também é usada na criação de tipos personalizados que estendem a ConfigurationSectionGroup classe .
Propriedades
Count |
Obtém o número de grupos da seção na coleção. |
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 ConfigurationSectionGroup cujo índice é especificado da coleção. |
Item[String] |
Obtém o objeto ConfigurationSectionGroup cujo nome é especificado da coleção. |
Keys |
Obtém as chaves para todos os objetos ConfigurationSectionGroup contidos nesse objeto ConfigurationSectionGroupCollection. |
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, ConfigurationSectionGroup) |
Adiciona um objeto ConfigurationSectionGroup a esse objeto ConfigurationSectionGroupCollection. |
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 |
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 a coleção. |
CopyTo(ConfigurationSectionGroup[], Int32) |
Copia esse objeto ConfigurationSectionGroupCollection para uma matriz. |
Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
Get(Int32) |
Obtém o objeto ConfigurationSectionGroup especificado contido na coleção. |
Get(String) |
Obtém o objeto ConfigurationSectionGroup especificado da coleção. |
GetEnumerator() |
Obtém um enumerador que pode iterar por meio do objeto ConfigurationSectionGroupCollection. |
GetHashCode() |
Serve como a função de hash padrão. (Herdado de Object) |
GetKey(Int32) |
Obtém a chave do objeto ConfigurationSectionGroup especificado contido neste objeto ConfigurationSectionGroupCollection. |
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 ConfigurationSectionGroup cujo nome é especificado desse objeto ConfigurationSectionGroupCollection. |
RemoveAt(Int32) |
Remove o objeto ConfigurationSectionGroup cujo índice é especificado desse objeto ConfigurationSectionGroupCollection. |
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. |