ConfigurationSection Class

定義

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

public abstract class ConfigurationSection : System.Configuration.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 'New
   
   
   ' 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 'ThrowIfReadOnly
   
   
   
   ' 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 'CustomSection 

下列範例是組態檔的摘錄,套用至先前的範例。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. 如需有關如何使用自訂組態區段,請參閱如何: 建立自訂組態區段使用 ConfigurationSectionFor 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.

給繼承者的注意事項

您可以使用程式設計方式或宣告式 (attributed) 程式撰寫模型來建立自訂組態區段:-程式設計模型。此模型需要針對每個區段的屬性建立屬性來取得或設定其值,並將它新增至基礎的內部屬性包ConfigurationElement基底類別。 宣告式模型。這個簡單的模型,也稱為屬性化的模型,可讓您使用屬性,並以屬性裝飾它定義區段的屬性。這些屬性會指示 ASP.NET 組態系統有關的屬性類型和其預設值。利用此資訊,透過反映取得 ASP.NET 組態系統會建立區段的屬性物件,並執行必要的初始化。Configuration類別允許以程式設計方式編輯組態檔的存取。您可以存取這些檔案進行讀取或寫入,如下所示:-讀取。您使用GetSection(String)GetSectionGroup(String)讀取組態資訊。請注意使用者讀取或處理序必須具有下列權限:-讀取組態檔,在目前的組態階層層級上的權限。 -讀取權限的所有父設定檔。如果您的應用程式需要它自己的設定唯讀存取,建議您使用GetSection多載的方法,在 Web 應用程式的情況下或GetSection(String)方法在用戶端應用程式的情況下。這些方法會提供存取目前的應用程式的快取的設定值,其具有較佳的效能比Configuration類別。

如果您使用靜態GetSection方法採用path參數,path參數必須參考的應用程式所在的程式碼執行; 否則會忽略此參數和目前執行的組態資訊應用程式會傳回。

-寫入。您可以使用其中一種Save寫入組態資訊的方法。請注意使用者寫入或處理序必須具有下列權限:-寫入組態檔,並在目前的組態階層層級目錄的權限。 -讀取所有的組態檔的權限。

You can use a programmatic or a declarative (attributed) coding model to create custom configuration sections: - Programmatic model. 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. These attributes instruct the ASP.NET configuration system about the property types and their default values. With this information, obtained through reflection, the ASP.NET configuration system creates the section property objects and performs the required initialization. The Configuration class allows programmatic access for editing configuration files. You can access these files for reading or writing as follows: - Reading. 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. 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. These methods provide access to the cached configuration values for the current application, which has better performance than the Configuration class.

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. 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.

(Inherited from ConfigurationElement)
ElementInformation

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

(Inherited from ConfigurationElement)
ElementProperty

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

(Inherited from ConfigurationElement)
EvaluationContext

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

(Inherited from ConfigurationElement)
HasContext

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

(Inherited from ConfigurationElement)
Item[ConfigurationProperty]

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

(Inherited from ConfigurationElement)
Item[String]

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

(Inherited from ConfigurationElement)
LockAllAttributesExcept

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

(Inherited from ConfigurationElement)
LockAllElementsExcept

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

(Inherited from ConfigurationElement)
LockAttributes

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

(Inherited from ConfigurationElement)
LockElements

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

(Inherited from ConfigurationElement)
LockItem

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

(Inherited from ConfigurationElement)
Properties

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

(Inherited from 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.

(Inherited from ConfigurationElement)
DeserializeSection(XmlReader)

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

Equals(Object)

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

(Inherited from ConfigurationElement)
GetHashCode()

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

(Inherited from ConfigurationElement)
GetRuntimeObject()

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

GetTransformedAssemblyString(String)

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

(Inherited from ConfigurationElement)
GetTransformedTypeString(String)

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

(Inherited from ConfigurationElement)
GetType()

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

(Inherited from Object)
Init()

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

(Inherited from ConfigurationElement)
InitializeDefault()

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

(Inherited from 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.

(Inherited from ConfigurationElement)
ListErrors(IList)

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

(Inherited from ConfigurationElement)
MemberwiseClone()

建立目前 Object 的淺層複製。 Creates a shallow copy of the current Object.

(Inherited from Object)
OnDeserializeUnrecognizedAttribute(String, String)

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

(Inherited from ConfigurationElement)
OnDeserializeUnrecognizedElement(String, XmlReader)

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

(Inherited from ConfigurationElement)
OnRequiredPropertyNotFound(String)

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

(Inherited from ConfigurationElement)
PostDeserialize()

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

(Inherited from ConfigurationElement)
PreSerialize(XmlWriter)

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

(Inherited from ConfigurationElement)
Reset(ConfigurationElement)

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

(Inherited from ConfigurationElement)
ResetModified()

在衍生類別中實作時,將 IsModified() 方法的值重設為 false Resets 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.

(Inherited from 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.

(Inherited from ConfigurationElement)
SetPropertyValue(ConfigurationProperty, Object, Boolean)

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

(Inherited from ConfigurationElement)
SetReadOnly()

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

(Inherited from 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.

(Inherited from Object)
Unmerge(ConfigurationElement, ConfigurationElement, ConfigurationSaveMode)

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

(Inherited from ConfigurationElement)

適用於

另請參閱