.NET Framework Class Library
ConfigurationPropertyAttribute Class

Declaratively instructs the .NET Framework to instantiate a configuration property. This class cannot be inherited.

Inheritance Hierarchy
SystemObject
   SystemAttribute
    System.ConfigurationConfigurationPropertyAttribute

Namespace:   System.Configuration
Assembly:  System.Configuration (in System.Configuration.dll)
Syntax
<[%$TOPIC/k92ha214_en-us_VS_110_2_0_0_0_0%]([%$TOPIC/k92ha214_en-us_VS_110_2_0_0_0_1%].Property)> _
Public NotInheritable Class ConfigurationPropertyAttribute _
	Inherits [%$TOPIC/k92ha214_en-us_VS_110_2_0_0_0_2%]
[[%$TOPIC/k92ha214_en-us_VS_110_2_0_1_0_0%]([%$TOPIC/k92ha214_en-us_VS_110_2_0_1_0_1%].Property)]
public sealed class ConfigurationPropertyAttribute : [%$TOPIC/k92ha214_en-us_VS_110_2_0_1_0_2%]
[[%$TOPIC/k92ha214_en-us_VS_110_2_0_2_0_0%]([%$TOPIC/k92ha214_en-us_VS_110_2_0_2_0_1%]::Property)]
public ref class ConfigurationPropertyAttribute sealed : public [%$TOPIC/k92ha214_en-us_VS_110_2_0_2_0_2%]
[<[%$TOPIC/k92ha214_en-us_VS_110_2_0_3_0_0%]>]
[<[%$TOPIC/k92ha214_en-us_VS_110_2_0_3_0_1%]([%$TOPIC/k92ha214_en-us_VS_110_2_0_3_0_2%].Property)>]
type ConfigurationPropertyAttribute =  
    class 
        inherit [%$TOPIC/k92ha214_en-us_VS_110_2_0_3_0_3%] 
    end

The ConfigurationPropertyAttribute type exposes the following members.

Constructors
  NameDescription
Public method ConfigurationPropertyAttributeInfrastructure. Initializes a new instance of ConfigurationPropertyAttribute class.
Top
Properties
  NameDescription
Public property DefaultValueGets or sets the default value for the decorated property.
Public property IsDefaultCollectionGets or sets a value indicating whether this is the default property collection for the decorated configuration property.
Public property IsKeyGets or sets a value indicating whether this is a key property for the decorated element property.
Public property IsRequiredGets or sets a value indicating whether the decorated element property is required.
Public property NameGets the name of the decorated configuration-element property.
Public property OptionsGets or sets the ConfigurationPropertyOptions for the decorated configuration-element property.
Public property TypeIdWhen implemented in a derived class, gets a unique identifier for this Attribute. (Inherited from Attribute.)
Top
Methods
  NameDescription
Public method EqualsInfrastructure. Returns a value that indicates whether this instance is equal to a specified object. (Inherited from Attribute.)
Public method GetHashCodeReturns the hash code for this instance. (Inherited from Attribute.)
Public method GetTypeGets the Type of the current instance. (Inherited from Object.)
Public method IsDefaultAttributeWhen overridden in a derived class, indicates whether the value of this instance is the default value for the derived class. (Inherited from Attribute.)
Public method MatchWhen overridden in a derived class, returns a value that indicates whether this instance equals a specified object. (Inherited from Attribute.)
Public method ToStringReturns a string that represents the current object. (Inherited from Object.)
Top
Explicit Interface Implementations
  NameDescription
Explicit interface implemetation Private method _AttributeGetIDsOfNamesMaps a set of names to a corresponding set of dispatch identifiers. (Inherited from Attribute.)
Explicit interface implemetation Private method _AttributeGetTypeInfoRetrieves the type information for an object, which can be used to get the type information for an interface. (Inherited from Attribute.)
Explicit interface implemetation Private method _AttributeGetTypeInfoCountRetrieves the number of type information interfaces that an object provides (either 0 or 1). (Inherited from Attribute.)
Explicit interface implemetation Private method _AttributeInvokeProvides access to properties and methods exposed by an object. (Inherited from Attribute.)
Top
Remarks

You use the ConfigurationPropertyAttribute to decorate a configuration property, which will instruct the .NET Framework to instantiate and to initialize the property using the value of the decorating parameter.

NoteNote

The simplest way to create a custom configuration element is to use the attributed (declarative) model. You declare the custom public properties and decorate them with the ConfigurationPropertyAttribute attribute. For each property marked with this attribute, the .NET Framework uses reflection to read the decorating parameters and create a related ConfigurationProperty instance. You can also use the programmatic model, in which case it is your responsibility to declare the custom public properties and return their collection.

The .NET Framework configuration system provides attribute types that you can use during the creation of custom configuration elements. There are two kinds of attribute types:

  1. The types instructing the .NET Framework how to instantiate the custom configuration-element properties. These types include:

  2. The types instructing the .NET Framework how to validate the custom configuration-element properties. These types include:

Examples

The following example shows how to define the properties of a custom ConfigurationSection object using the ConfigurationPropertyAttribute attribute.

The example contains two classes. The UrlsSection custom class uses the ConfigurationPropertyAttribute to define its own properties. The UsingConfigurationPropertyAttribute class uses the UrlsSection to read and write the custom section in the application configuration file.

Imports Microsoft.VisualBasic
Imports System
Imports System.Configuration


' Define a custom section. 
' This class shows how to use the ConfigurationPropertyAttribute. 
Public Class UrlsSection
    Inherits ConfigurationSection
    <ConfigurationProperty("name", DefaultValue:="Contoso", IsRequired:=True, IsKey:=True)>
    Public Property Name() As String 
        Get 
            Return CStr(Me("name"))
        End Get 
        Set(ByVal value As String)
            Me("name") = value
        End Set 
    End Property

    <ConfigurationProperty("url", DefaultValue:="http://www.contoso.com", IsRequired:=True), RegexStringValidator("\w+:\/\/[\w.]+\S*")>
    Public Property Url() As String 
        Get 
            Return CStr(Me("url"))
        End Get 
        Set(ByVal value As String)
            Me("url") = value
        End Set 
    End Property

    <ConfigurationProperty("port", DefaultValue:=0, IsRequired:=False), IntegerValidator(MinValue:=0, MaxValue:=8080, ExcludeRange:=False)>
    Public Property Port() As Integer 
        Get 
            Return CInt(Fix(Me("port")))
        End Get 
        Set(ByVal value As Integer)
            Me("port") = value
        End Set 
    End Property 
End Class
using System;
using System.Configuration;


// Define a custom section. 
// This class shows how to use the ConfigurationPropertyAttribute. 
public class UrlsSection : ConfigurationSection
{
    [ConfigurationProperty("name", DefaultValue = "Contoso",
        IsRequired = true, IsKey = true)]
    public string Name
    {
        get
        {
            return (string)this["name"];
        }
        set
        {
            this["name"] = value;
        }
    }

    [ConfigurationProperty("url", DefaultValue = "http://www.contoso.com",
        IsRequired = true)]
    [RegexStringValidator(@"\w+:\/\/[\w.]+\S*")]
    public string Url
    {
        get
        {
            return (string)this["url"];
        }
        set
        {
            this["url"] = value;
        }
    }

    [ConfigurationProperty("port", DefaultValue = (int)0, IsRequired = false)]
    [IntegerValidator(MinValue = 0, MaxValue = 8080, ExcludeRange = false)]
    public int Port
    {
        get
        {
            return (int)this["port"];
        }
        set
        {
            this["port"] = value;
        }
    }
}
Imports System
Imports System.Configuration

Public Class UsingConfigurationPropertyAttribute

    ' Create a custom section and save it in the  
    ' application configuration file. 
    Private Shared Sub CreateCustomSection()
        Try 

            ' Create a custom configuration section. 
            Dim customSection As New UrlsSection()

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

            ' Add the custom section to the application 
            ' configuration file. 
            If config.Sections("CustomSection") Is Nothing Then
                config.Sections.Add("CustomSection", customSection)
            End If 


            ' Save the application configuration file.
            customSection.SectionInformation.ForceSave = True
            config.Save(ConfigurationSaveMode.Modified)

            Console.WriteLine("Created custom section in the application configuration file: {0}", config.FilePath)
            Console.WriteLine()

        Catch err As ConfigurationErrorsException
            Console.WriteLine("CreateCustomSection: {0}", err.ToString())
        End Try 

    End Sub 

    Private Shared Sub ReadCustomSection()
        Try 
            ' Get the application configuration file. 
            Dim config As System.Configuration.Configuration = TryCast(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None), Configuration)

            ' Read and display the custom section. 
            Dim customSection As UrlsSection = TryCast(config.GetSection("CustomSection"), UrlsSection)
            Console.WriteLine("Reading custom section from the configuration file.")
            Console.WriteLine("Section name: {0}", customSection.Name)
            Console.WriteLine("Url: {0}", customSection.Url)
            Console.WriteLine("Port: {0}", customSection.Port)
            Console.WriteLine()
        Catch err As ConfigurationErrorsException
            Console.WriteLine("ReadCustomSection(string): {0}", err.ToString())
        End Try 

    End Sub 

    Shared Sub Main(ByVal args() As String)

        ' Get the name of the application. 
        Dim appName As String = Environment.GetCommandLineArgs()(0)

        ' Create a custom section and save it in the  
        ' application configuration file.
        CreateCustomSection()

        ' Read the custom section saved in the 
        ' application configuration file.
        ReadCustomSection()

        Console.WriteLine("Press enter to exit.")

        Console.ReadLine()
    End Sub 
End Class
using System;
using System.Configuration;

public class UsingConfigurationPropertyAttribute
{

    // Create a custom section and save it in the  
    // application configuration file. 
    static void CreateCustomSection()
    {
        try
        {

            // Create a custom configuration section.
            UrlsSection customSection = new UrlsSection();

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

            // Add the custom section to the application 
            // configuration file. 
            if (config.Sections["CustomSection"] == null)
            {
                config.Sections.Add("CustomSection", customSection);
            }


            // Save the application configuration file.
            customSection.SectionInformation.ForceSave = true;
            config.Save(ConfigurationSaveMode.Modified);

            Console.WriteLine("Created custom section in the application configuration file: {0}",
                config.FilePath);
            Console.WriteLine();

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

    }

    static void ReadCustomSection()
    {
        try
        {
            // Get the application configuration file.
            System.Configuration.Configuration config =
                    ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None) as Configuration;

            // Read and display the custom section.
            UrlsSection customSection =
                config.GetSection("CustomSection") as UrlsSection;
            Console.WriteLine("Reading custom section from the configuration file.");
            Console.WriteLine("Section name: {0}", customSection.Name);
            Console.WriteLine("Url: {0}", customSection.Url);
            Console.WriteLine("Port: {0}", customSection.Port);
            Console.WriteLine();
        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("ReadCustomSection(string): {0}", err.ToString());
        }

    }

    static void Main(string[] args)
    {

        // Get the name of the application. 
        string appName =
            Environment.GetCommandLineArgs()[0];

        // Create a custom section and save it in the  
        // application configuration file.
        CreateCustomSection();

        // Read the custom section saved in the 
        // application configuration file.
        ReadCustomSection();

        Console.WriteLine("Press enter to exit.");

        Console.ReadLine();
    }
}

The following is an excerpt of the configuration file containing the custom section as defined in the previous sample.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
        <section name="CustomSection" type="UrlsSection, UsingConfigurationPropertyAttribute, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
    </configSections>
    <CustomSection name="Contoso" url="http://www.contoso.com" />
</configuration>
Version Information

.NET Framework

Supported in: 4.5, 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1
Platforms

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Thread Safety
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.