ConfigurationSection 類別

定義

代表組態檔中的區段。Represents a section within a configuration file.

public ref class ConfigurationSection abstract : System::Configuration::ConfigurationElement
public abstract class ConfigurationSection : System.Configuration.ConfigurationElement
type ConfigurationSection = class
    inherit ConfigurationElement
Public MustInherit Class ConfigurationSection
Inherits ConfigurationElement
繼承
ConfigurationSection
衍生

範例

下列範例顯示如何以程式設計方式實作為自訂區段。The following example shows how to implement a custom section programmatically.

如需示範如何執行使用屬性化模型所執行之自訂區段的完整範例,請參閱ConfigurationElementFor a complete example that shows how to implement and use a custom section implemented using the attributed model, see ConfigurationElement.

// Define a custom section.
// The CustomSection type allows to define a custom section 
// programmatically.
public sealed class CustomSection : 
    ConfigurationSection
{
    // The collection (property bag) that contains 
    // the section properties.
    private static ConfigurationPropertyCollection _Properties;
    
    // Internal flag to disable 
    // property setting.
    private static bool _ReadOnly;

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

    // The MaxUsers 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;
        }
    }


    private new bool IsReadOnly
    {
        get
        {
            return _ReadOnly;
        }
    }

    // Use this to disable property setting.
    private void ThrowIfReadOnly(string propertyName)
    {
        if (IsReadOnly)
            throw new ConfigurationErrorsException(
                "The property " + propertyName + " is read only.");
    }


    // Customizes the use of CustomSection
    // by setting _ReadOnly to false.
    // Remember you must use it along with ThrowIfReadOnly.
    protected override object GetRuntimeObject()
    {
        // To enable property setting just assign true to
        // the following flag.
        _ReadOnly = true;
        return base.GetRuntimeObject();
    }


    [StringValidator(InvalidCharacters = " ~!@#$%^&*()[]{}/;'\"|\\",
        MinLength = 1, MaxLength = 60)]
    public string FileName
    {
        get
        {
            return (string)this["fileName"];
        }
        set
        {
            // With this you disable the setting.
            // Remember that the _ReadOnly flag must
            // be set to true in the GetRuntimeObject.
            ThrowIfReadOnly("FileName");
            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;
        }
    }
   
    
}
' Define a custom section.
' The CustomSection type allows to define a custom section 
' programmatically.

NotInheritable Public Class CustomSection
   Inherits ConfigurationSection
   ' The collection (property bag) that contains 
   ' the section properties.
   Private Shared _Properties As ConfigurationPropertyCollection
   
   ' Internal flag to disable 
   ' property setting.
   Private Shared _ReadOnly As Boolean
   
   ' The FileName property.
    Private Shared _FileName As New ConfigurationProperty( _
    "fileName", GetType(String), _
    "default.txt", _
    ConfigurationPropertyOptions.IsRequired)
   
   ' The MaxUsers property.
    Private Shared _MaxUsers As New ConfigurationProperty( _
    "maxUsers", GetType(Long), _
    CType(1000, Long), _
    ConfigurationPropertyOptions.None)
   
   ' The MaxIdleTime property.
    Private Shared _MaxIdleTime As New ConfigurationProperty( _
    "maxIdleTime", GetType(TimeSpan), _
    TimeSpan.FromMinutes(5), _
    ConfigurationPropertyOptions.IsRequired)
   
   
   ' CustomSection constructor.
   Public Sub New()
      ' Property initialization
        _Properties = _
        New ConfigurationPropertyCollection()
      
      _Properties.Add(_FileName)
      _Properties.Add(_MaxUsers)
      _Properties.Add(_MaxIdleTime)
   End Sub
   
   
   ' This is a key customization. 
   ' It returns the initialized property bag.
    Protected Overrides ReadOnly Property Properties() _
    As ConfigurationPropertyCollection
        Get
            Return _Properties
        End Get
    End Property
   
   
   
   Private Shadows ReadOnly Property IsReadOnly() As Boolean
      Get
         Return _ReadOnly
      End Get
   End Property
   
   
   ' Use this to disable property setting.
   Private Sub ThrowIfReadOnly(propertyName As String)
      If IsReadOnly Then
            Throw New ConfigurationErrorsException( _
            "The property " + propertyName + " is read only.")
      End If
   End Sub
   
   
   
   ' Customizes the use of CustomSection
    ' by setting _ReadOnly to false.
   ' Remember you must use it along with ThrowIfReadOnly.
   Protected Overrides Function GetRuntimeObject() As Object
      ' To enable property setting just assign true to
      ' the following flag.
      _ReadOnly = True
      Return MyBase.GetRuntimeObject()
   End Function 'GetRuntimeObject
   
   
    <StringValidator( _
    InvalidCharacters:=" ~!@#$%^&*()[]{}/;'""|\", _
    MinLength:=1, MaxLength:=60)> _
    Public Property FileName() As String
        Get
            Return CStr(Me("fileName"))
        End Get
        Set(ByVal value As String)
            ' With this you disable the setting.
            ' Remember that the _ReadOnly flag must
            ' be set to true in the GetRuntimeObject.
            ThrowIfReadOnly("FileName")
            Me("fileName") = value
        End Set
    End Property
   
   
    <LongValidator( _
    MinValue:=1, MaxValue:=1000000, _
    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
   
   
    <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

下列範例是設定檔的摘錄,因為它適用于先前的範例。The following example is an excerpt of the configuration file as it applies to the previous example.

<?xml version="1.0" encoding="utf-8"?>
 <configuration>  
   <configSections>
     <section name="CustomSection" type="Samples.AspNet. CustomSection, CustomConfigurationSection, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" allowDefinition="Everywhere" allowExeDefinition="MachineToApplication" restartOnExternalChanges="true" />
   </configSections>  

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

 </configuration>

備註

您可以使用ConfigurationSection類別來執行自訂區段類型。You use the ConfigurationSection class to implement a custom section type. ConfigurationSection擴充類別,以提供自訂處理和以程式設計方式存取自訂設定區段。Extend the ConfigurationSection class to provide custom handling and programmatic access to custom configuration sections. 如需如何使用自訂設定區段的詳細資訊,請參閱如何:使用 ConfigurationSection建立自訂設定區段。For information about how use custom configuration sections, see How to: Create Custom Configuration Sections Using ConfigurationSection.

區段會向configSections元素中的專案註冊其處理類型。A section registers its handling type with an entry in the configSections element. 如需範例,請參閱範例一節中所示的設定檔摘錄。For an example, see the configuration file excerpt shown in the Example section.

注意

在舊版的 .NET Framework 中,設定區段處理常式是用來以程式設計方式變更設定。In previous versions of the .NET Framework, configuration section handlers were used to make changes to configuration settings programmatically. 現在,所有的預設設定區段都會以擴充ConfigurationSection類別的類別來表示。Now, all the default configuration sections are represented by classes that extend the ConfigurationSection class.

給繼承者的注意事項

您可以使用程式設計或宣告式(屬性化)編碼模型來建立自訂設定區段:You can use a programmatic or a declarative (attributed) coding model to create custom configuration sections: -程式設計模型。- Programmatic model. 此模型需要針對每個區段屬性建立屬性,以取得或設定其值,並將它加入至基礎ConfigurationElement基類的內部屬性包。This model requires that for each section attribute you create a property to get or set its value and add it to the internal property bag of the underlying ConfigurationElement base class.

-宣告式模型。- Declarative model. 這個較簡單的模型也稱為屬性化模型,可讓您使用屬性來定義區段屬性,並以屬性裝飾。This simpler model, also called the attributed model, allows you to define a section attribute by using a property and decorating it with attributes. 這些屬性會指示 ASP.NET 設定系統有關屬性類型及其預設值的資訊。These attributes instruct the ASP.NET configuration system about the property types and their default values. 透過反映取得的這種資訊,ASP.NET 設定系統會建立區段屬性物件,並執行必要的初始化。With this information, obtained through reflection, the ASP.NET configuration system creates the section property objects and performs the required initialization.

Configuration類別可讓您以程式設計方式存取編輯設定檔。The Configuration class allows programmatic access for editing configuration files. 您可以存取這些檔案以進行讀取或寫入,如下所示:You can access these files for reading or writing as follows: 讀.- Reading. 您可以GetSection(String)使用GetSectionGroup(String)或來讀取設定資訊。You use GetSection(String) or GetSectionGroup(String) to read configuration information. 請注意,讀取的使用者或處理常式必須具有下列許可權:Note that the user or process that reads must have the following permissions: -位於目前設定階層層級之設定檔的讀取權限。- Read permission on the configuration file at the current configuration hierarchy level.

-所有父設定檔的讀取權限。- Read permissions on all the parent configuration files.

如果您的應用程式需要唯讀存取自己的設定,建議您在 Web 應用程式的GetSection情況下使用多載的方法, GetSection(String)或在用戶端應用程式的情況下使用此方法。If your application needs read-only access to its own configuration, it is recommended you use the GetSection overloaded methods in the case of Web applications, or the GetSection(String) method in the case of client applications.

這些方法可讓您存取目前應用程式的快取設定值,其效能高於Configuration類別。These methods provide access to the cached configuration values for the current application, which has better performance than the Configuration class.


如果您使用path接受參數GetSection的靜態方法,則path參數必須參考程式碼執行所在的應用程式; 否則,會忽略參數,以及目前正在執行之的設定資訊。傳回應用程式。If you use a static GetSection method that takes a path parameter, the path parameter must refer to the application in which the code is running; otherwise, the parameter is ignored and configuration information for the currently-running application is returned.

本文.- Writing. 您可以使用其中一Save種方法來寫入設定資訊。You use one of the Save methods to write configuration information. 請注意,寫入的使用者或處理常式必須具有下列許可權:Note that the user or process that writes must have the following permissions: -設定檔案和目錄(位於目前設定階層層級)的寫入權限。- Write permission on the configuration file and directory at the current configuration hierarchy level. -所有設定檔的讀取權限。- Read permissions on all the configuration files.

建構函式

ConfigurationSection()

初始化 ConfigurationSection 類別的新執行個體。Initializes a new instance of the ConfigurationSection class.

屬性

CurrentConfiguration

取得最上層 Configuration 執行個體的參考,這個執行個體表示目前 ConfigurationElement 執行個體所屬的組態階層架構。Gets a reference to the top-level Configuration instance that represents the configuration hierarchy that the current ConfigurationElement instance belongs to.

(繼承來源 ConfigurationElement)
ElementInformation

取得 ElementInformation 物件,其中包含 ConfigurationElement 物件之不可自訂的資訊和功能。Gets an ElementInformation object that contains the non-customizable information and functionality of the ConfigurationElement object.

(繼承來源 ConfigurationElement)
ElementProperty

取得表示 ConfigurationElementProperty 物件本身的 ConfigurationElement 物件。Gets the ConfigurationElementProperty object that represents the ConfigurationElement object itself.

(繼承來源 ConfigurationElement)
EvaluationContext

取得 ConfigurationElement 物件的 ContextInformation 物件。Gets the ContextInformation object for the ConfigurationElement object.

(繼承來源 ConfigurationElement)
HasContext

取得值,指出 CurrentConfiguration 屬性是否為 nullGets a value that indicates whether the CurrentConfiguration property is null.

(繼承來源 ConfigurationElement)
Item[ConfigurationProperty]

取得或設定此組態項目的屬性 (Property) 或屬性 (Attribute)。Gets or sets a property or attribute of this configuration element.

(繼承來源 ConfigurationElement)
Item[String]

取得或設定此一組態項目的屬性或子項目。Gets or sets a property, attribute, or child element of this configuration element.

(繼承來源 ConfigurationElement)
LockAllAttributesExcept

取得已鎖定屬性的集合。Gets the collection of locked attributes.

(繼承來源 ConfigurationElement)
LockAllElementsExcept

取得已鎖定項目的集合。Gets the collection of locked elements.

(繼承來源 ConfigurationElement)
LockAttributes

取得已鎖定屬性的集合。Gets the collection of locked attributes.

(繼承來源 ConfigurationElement)
LockElements

取得已鎖定項目的集合。Gets the collection of locked elements.

(繼承來源 ConfigurationElement)
LockItem

取得或設定值,指出此項目是否已被鎖定。Gets or sets a value indicating whether the element is locked.

(繼承來源 ConfigurationElement)
Properties

取得屬性的集合。Gets the collection of properties.

(繼承來源 ConfigurationElement)
SectionInformation

取得 SectionInformation 物件,該物件包含 ConfigurationSection 物件之不可自訂的資訊和功能。Gets a SectionInformation object that contains the non-customizable information and functionality of the ConfigurationSection object.

方法

DeserializeElement(XmlReader, Boolean)

從組態檔讀取 XML。Reads XML from the configuration file.

(繼承來源 ConfigurationElement)
DeserializeSection(XmlReader)

從組態檔讀取 XML。Reads XML from the configuration file.

Equals(Object)

將目前的 ConfigurationElement 執行個體與指定的物件相比較。Compares the current ConfigurationElement instance to the specified object.

(繼承來源 ConfigurationElement)
GetHashCode()

取得表示目前 ConfigurationElement 執行個體的唯一值。Gets a unique value representing the current ConfigurationElement instance.

(繼承來源 ConfigurationElement)
GetRuntimeObject()

在衍生類別中覆寫時,傳回自訂物件。Returns a custom object when overridden in a derived class.

GetTransformedAssemblyString(String)

傳回指定之組件名稱的轉換版本。Returns the transformed version of the specified assembly name.

(繼承來源 ConfigurationElement)
GetTransformedTypeString(String)

傳回指定之型別名稱的轉換版本。Returns the transformed version of the specified type name.

(繼承來源 ConfigurationElement)
GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)
Init()

ConfigurationElement 物件設定為它的初始狀態。Sets the ConfigurationElement object to its initial state.

(繼承來源 ConfigurationElement)
InitializeDefault()

用來初始化 ConfigurationElement 物件的預設值集。Used to initialize a default set of values for the ConfigurationElement object.

(繼承來源 ConfigurationElement)
IsModified()

在衍生類別中進行實作時,指出這個組態項目自上次儲存或載入後是否已修改。Indicates whether this configuration element has been modified since it was last saved or loaded when implemented in a derived class.

IsReadOnly()

取得值,這個值表示 ConfigurationElement 物件是否唯讀。Gets a value indicating whether the ConfigurationElement object is read-only.

(繼承來源 ConfigurationElement)
ListErrors(IList)

將這個 ConfigurationElement 物件中和所有子項目中的無效屬性錯誤加入傳遞的清單。Adds the invalid-property errors in this ConfigurationElement object, and in all subelements, to the passed list.

(繼承來源 ConfigurationElement)
MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(繼承來源 Object)
OnDeserializeUnrecognizedAttribute(String, String)

取得值,指出在還原序列化程序中是否遇到未知的屬性 (Attribute)。Gets a value indicating whether an unknown attribute is encountered during deserialization.

(繼承來源 ConfigurationElement)
OnDeserializeUnrecognizedElement(String, XmlReader)

取得值,指出在還原序列化程序中是否遇到未知的項目。Gets a value indicating whether an unknown element is encountered during deserialization.

(繼承來源 ConfigurationElement)
OnRequiredPropertyNotFound(String)

在找不到必要的屬性時擲回例外狀況 (Exception)。Throws an exception when a required property is not found.

(繼承來源 ConfigurationElement)
PostDeserialize()

還原序列化之後呼叫。Called after deserialization.

(繼承來源 ConfigurationElement)
PreSerialize(XmlWriter)

序列化之前呼叫。Called before serialization.

(繼承來源 ConfigurationElement)
Reset(ConfigurationElement)

重設 ConfigurationElement 物件的內部狀態,包括鎖定和屬性的集合。Resets the internal state of the ConfigurationElement object, including the locks and the properties collections.

(繼承來源 ConfigurationElement)
ResetModified()

在衍生類別中實作時,將 IsModified() 方法的值重設為 falseResets the value of the IsModified() method to false when implemented in a derived class.

SerializeElement(XmlWriter, Boolean)

在衍生類別中實作時,將此組態項目的內容寫入組態檔中。Writes the contents of this configuration element to the configuration file when implemented in a derived class.

(繼承來源 ConfigurationElement)
SerializeSection(ConfigurationElement, String, ConfigurationSaveMode)

建立 XML 字串,在該字串的單一區段中,包含了要寫入檔案之 ConfigurationSection 物件的取消合併檢視。Creates an XML string containing an unmerged view of the ConfigurationSection object as a single section to write to a file.

SerializeToXmlElement(XmlWriter, String)

在衍生類別中實作時,將此組態項目的外部標記寫入組態檔中。Writes the outer tags of this configuration element to the configuration file when implemented in a derived class.

(繼承來源 ConfigurationElement)
SetPropertyValue(ConfigurationProperty, Object, Boolean)

將屬性設定為指定的值。Sets a property to the specified value.

(繼承來源 ConfigurationElement)
SetReadOnly()

設定 IsReadOnly() 物件和所有子項目的 ConfigurationElement 屬性。Sets the IsReadOnly() property for the ConfigurationElement object and all subelements.

(繼承來源 ConfigurationElement)
ShouldSerializeElementInTargetVersion(ConfigurationElement, String, FrameworkName)

表示指定的項目是否應該在組態物件階層架構針對指定的 .NET Framework.NET Framework 目標版本序列化時予以序列化。Indicates whether the specified element should be serialized when the configuration object hierarchy is serialized for the specified target version of the .NET Framework.NET Framework.

ShouldSerializePropertyInTargetVersion(ConfigurationProperty, String, FrameworkName, ConfigurationElement)

表示指定的屬性是否應該在組態物件階層架構針對指定的 .NET Framework.NET Framework 目標版本序列化時予以序列化。Indicates whether the specified property should be serialized when the configuration object hierarchy is serialized for the specified target version of the .NET Framework.NET Framework.

ShouldSerializeSectionInTargetVersion(FrameworkName)

表示目前的 ConfigurationSection 執行個體是否應該在組態物件階層架構針對指定的 .NET Framework.NET Framework 目標版本序列化時予以序列化。Indicates whether the current ConfigurationSection instance should be serialized when the configuration object hierarchy is serialized for the specified target version of the .NET Framework.NET Framework.

ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 Object)
Unmerge(ConfigurationElement, ConfigurationElement, ConfigurationSaveMode)

修改 ConfigurationElement 物件,以移除不應該儲存的所有值。Modifies the ConfigurationElement object to remove all values that should not be saved.

(繼承來源 ConfigurationElement)

適用於

另請參閱