Configuration Класс

Определение

Представляет файл конфигурации, применимый к конкретному компьютеру, приложению или ресурсу. Этот класс не наследуется.

public ref class Configuration sealed
public sealed class Configuration
type Configuration = class
Public NotInheritable Class Configuration
Наследование
Configuration

Примеры

В следующем примере кода показано, как использовать класс для Configuration доступа к элементам файла конфигурации.

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Globalization;
using System.ComponentModel;
using System.Collections.Specialized;

// Before compiling this application, 
// remember to reference the System.Configuration assembly in your project. 
#region CustomSection class

// Define a custom section. This class is used to
// populate the configuration file.
// It creates the following custom section:
//  <CustomSection name="Contoso" url="http://www.contoso.com" port="8080" />.
public sealed class CustomSection : ConfigurationSection
{

    public CustomSection()
    {
    }

    [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)8080,
        IsRequired = false)]
    [IntegerValidator(MinValue = 0,
        MaxValue = 8080, ExcludeRange = false)]
    public int Port
    {
        get
        {
            return (int)this["port"];
        }
        set
        {
            this["port"] = value;
        }
    }
}

#endregion

#region Using Configuration Class
class UsingConfigurationClass
{


    // Show how to create an instance of the Configuration class
    // that represents this application configuration file.  
    static void CreateConfigurationFile()
    {
        try
        {

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

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

            // Create the custom section entry  
            // in <configSections> group and the 
            // related target section in <configuration>.
            if (config.Sections["CustomSection"] == null)
            {
                config.Sections.Add("CustomSection", customSection);
            }

            // Create and add an entry to appSettings section.
            
            string conStringname="LocalSqlServer";
            string conString = @"data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true";
            string providerName="System.Data.SqlClient";

            ConnectionStringSettings connStrSettings = new ConnectionStringSettings();
            connStrSettings.Name = conStringname;
            connStrSettings.ConnectionString= conString;
            connStrSettings.ProviderName = providerName;

            config.ConnectionStrings.ConnectionStrings.Add(connStrSettings);
            
            // Add an entry to appSettings section.
            int appStgCnt =
                ConfigurationManager.AppSettings.Count;
            string newKey = "NewKey" + appStgCnt.ToString();

            string newValue = DateTime.Now.ToLongDateString() +
              " " + DateTime.Now.ToLongTimeString();

            config.AppSettings.Settings.Add(newKey, newValue);

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

            Console.WriteLine("Created configuration file: {0}",
                config.FilePath);
        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("CreateConfigurationFile: {0}", err.ToString());
        }
    }

    // Show how to use the GetSection(string) method.
    static void GetCustomSection()
    {
        try
        {

            CustomSection customSection;

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

            customSection =
                config.GetSection("CustomSection") as CustomSection;

            Console.WriteLine("Section name: {0}", customSection.Name);
            Console.WriteLine("Url: {0}", customSection.Url);
            Console.WriteLine("Port: {0}", customSection.Port);
        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("Using GetSection(string): {0}", err.ToString());
        }
    }


    // Show how to use different modalities to save 
    // a configuration file.
    static void SaveConfigurationFile()
    {
        try
        {

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

            // Save the full configuration file and force save even if the file was not modified.
            config.SaveAs("MyConfigFull.config", ConfigurationSaveMode.Full, true);
            Console.WriteLine("Saved config file as MyConfigFull.config using the mode: {0}",
                ConfigurationSaveMode.Full.ToString());

            config =
                    ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None) as Configuration;

            // Save only the part of the configuration file that was modified. 
            config.SaveAs("MyConfigModified.config", ConfigurationSaveMode.Modified, true);
            Console.WriteLine("Saved config file as MyConfigModified.config using the mode: {0}",
                ConfigurationSaveMode.Modified.ToString());

            config =
                    ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None) as Configuration;

            // Save the full configuration file.
            config.SaveAs("MyConfigMinimal.config");
            Console.WriteLine("Saved config file as MyConfigMinimal.config using the mode: {0}",
                ConfigurationSaveMode.Minimal.ToString());
        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("SaveConfigurationFile: {0}", err.ToString());
        }
    }

    // Show how use the AppSettings and ConnectionStrings 
    // properties.
    static void GetSections(string section)
    {
        try
        {

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

            // Get the selected section.
            switch (section)
            {
                case "appSettings":
                    try
                    {
                        AppSettingsSection appSettings =
                            config.AppSettings as AppSettingsSection;
                        Console.WriteLine("Section name: {0}",
                                appSettings.SectionInformation.SectionName);

                        // Get the AppSettings section elements.
                        Console.WriteLine();
                        Console.WriteLine("Using AppSettings property.");
                        Console.WriteLine("Application settings:");
                        // Get the KeyValueConfigurationCollection 
                        // from the configuration.
                        KeyValueConfigurationCollection settings =
                          config.AppSettings.Settings;

                        // Display each KeyValueConfigurationElement.
                        foreach (KeyValueConfigurationElement keyValueElement in settings)
                        {
                            Console.WriteLine("Key: {0}", keyValueElement.Key);
                            Console.WriteLine("Value: {0}", keyValueElement.Value);
                            Console.WriteLine();
                        }
                    }
                    catch (ConfigurationErrorsException e)
                    {
                        Console.WriteLine("Using AppSettings property: {0}",
                            e.ToString());
                    }
                    break;

                case "connectionStrings":
                    ConnectionStringsSection
                        conStrSection =
                        config.ConnectionStrings as ConnectionStringsSection;
                    Console.WriteLine("Section name: {0}",
                        conStrSection.SectionInformation.SectionName);

                    try
                    {
                        if (conStrSection.ConnectionStrings.Count != 0)
                        {
                            Console.WriteLine();
                            Console.WriteLine("Using ConnectionStrings property.");
                            Console.WriteLine("Connection strings:");

                            // Get the collection elements.
                            foreach (ConnectionStringSettings connection in
                              conStrSection.ConnectionStrings)
                            {
                                string name = connection.Name;
                                string provider = connection.ProviderName;
                                string connectionString = connection.ConnectionString;

                                Console.WriteLine("Name:               {0}",
                                  name);
                                Console.WriteLine("Connection string:  {0}",
                                  connectionString);
                                Console.WriteLine("Provider:            {0}",
                                   provider);
                            }
                        }
                    }
                    catch (ConfigurationErrorsException e)
                    {
                        Console.WriteLine("Using ConnectionStrings property: {0}",
                            e.ToString());
                    }
                    break;

                default:
                    Console.WriteLine(
                        "GetSections: Unknown section (0)", section);
                    break;
            }
        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("GetSections: (0)", err.ToString());
        }
    }

    // Show how to use the Configuration object properties 
    // to obtain configuration file information.
    static void GetConfigurationInformation()
    {
        try
        {

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

            Console.WriteLine("Reading configuration information:");

            ContextInformation evalContext =
                config.EvaluationContext as ContextInformation;
            Console.WriteLine("Machine level: {0}",
                evalContext.IsMachineLevel.ToString());
                    
            string filePath = config.FilePath;
            Console.WriteLine("File path: {0}", filePath);
             
            bool hasFile = config.HasFile;
            Console.WriteLine("Has file: {0}", hasFile.ToString());

            ConfigurationSectionGroupCollection
                groups = config.SectionGroups;
            Console.WriteLine("Groups: {0}", groups.Count.ToString());
            foreach (ConfigurationSectionGroup group in groups)
            {
                Console.WriteLine("Group Name: {0}", group.Name);
               // Console.WriteLine("Group Type: {0}", group.Type);
            }

            ConfigurationSectionCollection
                sections = config.Sections;
            Console.WriteLine("Sections: {0}", sections.Count.ToString());
        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("GetConfigurationInformation: {0}",err.ToString());
        }
    }

#endregion 

#region Application Main
    //*** User Interaction Class ***//

    // Obtain user's input and provide feedback.
    // This class contains the application Main() function.
    // It calls the ConfigurationManager methods based 
    // on the user's selection.
    class ApplicationMain
    {
        // Display user's menu.
        public static void UserMenu()
        {
            string applicationName =
                Environment.GetCommandLineArgs()[0] + ".exe";
            StringBuilder buffer = new StringBuilder();

            buffer.AppendLine("Application: " + applicationName);
            buffer.AppendLine("Make your selection.");
            buffer.AppendLine("?    -- Display help.");
            buffer.AppendLine("Q,q  -- Exit the application.");
            
            buffer.Append("1    -- Instantiate the");
            buffer.AppendLine(" Configuration class.");

            buffer.Append("2    -- Use GetSection(string) to read ");
            buffer.AppendLine(" a custom section.");
            
            buffer.Append("3    -- Use SaveAs methods");
            buffer.AppendLine(" to save the configuration file.");

            buffer.Append("4    -- Use AppSettings property to read");
            buffer.AppendLine(" the appSettings section.");
            buffer.Append("5    -- Use ConnectionStrings property to read");
            buffer.AppendLine(" the connectionStrings section.");

            buffer.Append("6    -- Use Configuration class properties");
            buffer.AppendLine(" to obtain configuration information.");

            Console.Write(buffer.ToString());
        }

        // Obtain user's input and provide
        // feedback.
        static void Main(string[] args)
        {
            // Define user selection string.
            string selection;

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

            // Get user selection.
            while (true)
            {

                UserMenu();
                Console.Write("> ");
                selection = Console.ReadLine();
                if (!string.IsNullOrEmpty(selection))
                    break;
            }

            while (selection.ToLower() != "q")
            {
                // Process user's input.
                switch (selection)
                {
                    case "1":
                        // Show how to create an instance of the Configuration class.
                        CreateConfigurationFile();
                        break;

                    case "2":
                        // Show how to use GetSection(string) method.
                        GetCustomSection();
                        break;

                    case "3":
                        // Show how to use ConnectionStrings.
                        SaveConfigurationFile();
                        break;

                    case "4":
                        // Show how to use the AppSettings property.
                        GetSections("appSettings");
                        break;

                    case "5":
                        // Show how to use the ConnectionStrings property.
                        GetSections("connectionStrings");
                        break;

                    case "6":
                        // Show how to obtain configuration file information.
                        GetConfigurationInformation();
                        break;

                    default:
                        UserMenu();
                        break;
                }
                Console.Write("> ");
                selection = Console.ReadLine();
            }
        }
    }
#endregion

}
Imports System.Text
Imports System.Configuration
Imports System.Globalization
Imports System.ComponentModel
Imports System.Collections.Specialized

' Before compiling this application, 
' remember to reference the System.Configuration assembly in your project. 
#Region "CustomSection class"

' Define a custom section. This class is used to
' populate the configuration file.
' It creates the following custom section:
'  <CustomSection name="Contoso" url="http://www.contoso.com" port="8080" />.
Public NotInheritable Class CustomSection
    Inherits ConfigurationSection

    Public Sub New()

    End Sub


    <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:=CInt(8080), 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

#End Region

#Region "Using Configuration Class"
Friend Class UsingConfigurationClass

    ' Show how to create an instance of the Configuration class
    ' that represents this application configuration file.  
    Public Shared Sub CreateConfigurationFile()
        Try

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

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

            ' Create the section entry  
            ' in <configSections> and the 
            ' related target section in <configuration>.
            If config.Sections("CustomSection") Is Nothing Then
                config.Sections.Add("CustomSection", customSection)
            End If

            ' Create and add an entry to appSettings section.

            Dim conStringname As String = "LocalSqlServer"
            Dim conString As String = "data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
            Dim providerName As String = "System.Data.SqlClient"

            Dim connStrSettings As New ConnectionStringSettings()
            connStrSettings.Name = conStringname
            connStrSettings.ConnectionString = conString
            connStrSettings.ProviderName = providerName

            config.ConnectionStrings.ConnectionStrings.Add(connStrSettings)

            ' Add an entry to appSettings section.
            Dim appStgCnt As Integer = ConfigurationManager.AppSettings.Count
            Dim newKey As String = "NewKey" & appStgCnt.ToString()

            Dim newValue As String = Date.Now.ToLongDateString() & " " & Date.Now.ToLongTimeString()

            config.AppSettings.Settings.Add(newKey, newValue)

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

            Console.WriteLine("Created configuration file: {0}", config.FilePath)

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

    End Sub

    ' Show how to use the GetSection(string) method.
    Public Shared Sub GetCustomSection()
        Try

            Dim customSection As CustomSection

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

            customSection = TryCast(config.GetSection("CustomSection"), CustomSection)

            Console.WriteLine("Section name: {0}", customSection.Name)
            Console.WriteLine("Url: {0}", customSection.Url)
            Console.WriteLine("Port: {0}", customSection.Port)

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

    End Sub


    ' Show how to use different modalities to save 
    ' a configuration file.
    Public Shared Sub SaveConfigurationFile()
        Try

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

            ' Save the full configuration file and force save even if the file was not modified.
            config.SaveAs("MyConfigFull.config", ConfigurationSaveMode.Full, True)
            Console.WriteLine("Saved config file as MyConfigFull.config using the mode: {0}", ConfigurationSaveMode.Full.ToString())

            config = TryCast(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None), Configuration)

            ' Save only the part of the configuration file that was modified. 
            config.SaveAs("MyConfigModified.config", ConfigurationSaveMode.Modified, True)
            Console.WriteLine("Saved config file as MyConfigModified.config using the mode: {0}", ConfigurationSaveMode.Modified.ToString())

            config = TryCast(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None), Configuration)

            ' Save the full configuration file.
            config.SaveAs("MyConfigMinimal.config")
            Console.WriteLine("Saved config file as MyConfigMinimal.config using the mode: {0}", ConfigurationSaveMode.Minimal.ToString())

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

    End Sub


    ' Show how use the AppSettings and ConnectionStrings 
    ' properties.
    Public Shared Sub GetSections(ByVal section As String)
        Try

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

            ' Get the selected section.
            Select Case section
                Case "appSettings"
                    Try
                        Dim appSettings As AppSettingsSection = TryCast(config.AppSettings, AppSettingsSection)
                        Console.WriteLine("Section name: {0}", appSettings.SectionInformation.SectionName)

                        ' Get the AppSettings section elements.
                        Console.WriteLine()
                        Console.WriteLine("Using AppSettings property.")
                        Console.WriteLine("Application settings:")
                        ' Get the KeyValueConfigurationCollection 
                        ' from the configuration.
                        Dim settings As KeyValueConfigurationCollection = config.AppSettings.Settings

                        ' Display each KeyValueConfigurationElement.
                        For Each keyValueElement As KeyValueConfigurationElement In settings
                            Console.WriteLine("Key: {0}", keyValueElement.Key)
                            Console.WriteLine("Value: {0}", keyValueElement.Value)
                            Console.WriteLine()
                        Next keyValueElement
                    Catch e As ConfigurationErrorsException
                        Console.WriteLine("Using AppSettings property: {0}", e.ToString())
                    End Try

                Case "connectionStrings"
                    Dim conStrSection As ConnectionStringsSection = TryCast(config.ConnectionStrings, ConnectionStringsSection)
                    Console.WriteLine("Section name: {0}", conStrSection.SectionInformation.SectionName)

                    Try
                        If conStrSection.ConnectionStrings.Count <> 0 Then
                            Console.WriteLine()
                            Console.WriteLine("Using ConnectionStrings property.")
                            Console.WriteLine("Connection strings:")

                            ' Get the collection elements.
                            For Each connection As ConnectionStringSettings In conStrSection.ConnectionStrings
                                Dim name As String = connection.Name
                                Dim provider As String = connection.ProviderName
                                Dim connectionString As String = connection.ConnectionString

                                Console.WriteLine("Name:               {0}", name)
                                Console.WriteLine("Connection string:  {0}", connectionString)
                                Console.WriteLine("Provider:            {0}", provider)
                            Next connection
                        End If
                    Catch e As ConfigurationErrorsException
                        Console.WriteLine("Using ConnectionStrings property: {0}", e.ToString())
                    End Try

                Case Else
                    Console.WriteLine("GetSections: Unknown section (0)", section)
            End Select

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

    End Sub

    ' Show how to use the Configuration object properties 
    ' to obtain configuration file information.
    Public Shared Sub GetConfigurationInformation()
        Try

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

            Console.WriteLine("Reading configuration information:")

            Dim evalContext As ContextInformation = TryCast(config.EvaluationContext, ContextInformation)
            Console.WriteLine("Machine level: {0}", evalContext.IsMachineLevel.ToString())

            Dim filePath As String = config.FilePath
            Console.WriteLine("File path: {0}", filePath)

            Dim hasFile As Boolean = config.HasFile
            Console.WriteLine("Has file: {0}", hasFile.ToString())


            Dim groups As ConfigurationSectionGroupCollection = config.SectionGroups
            Console.WriteLine("Groups: {0}", groups.Count.ToString())
            For Each group As ConfigurationSectionGroup In groups
                Console.WriteLine("Group Name: {0}", group.Name)
                ' Console.WriteLine("Group Type: {0}", group.Type);
            Next group


            Dim sections As ConfigurationSectionCollection = config.Sections
            Console.WriteLine("Sections: {0}", sections.Count.ToString())


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

    End Sub
End Class

#End Region

#Region "Application Main"
'*** User Interaction Class ***//

' Obtain user's input and provide feedback.
' This class contains the application Main() function.
' It calls the ConfigurationManager methods based 
' on the user's selection.
Public Class ApplicationMain
    ' Display user's menu.
    Public Shared Sub UserMenu()
        Dim applicationName As String = Environment.GetCommandLineArgs()(0) & ".exe"
        Dim buffer As New StringBuilder()

        buffer.AppendLine("Application: " & applicationName)
        buffer.AppendLine("Please, make your selection.")
        buffer.AppendLine("?    -- Display help.")
        buffer.AppendLine("Q,q  -- Exit the application.")

        buffer.Append("1    -- Instantiate the")
        buffer.AppendLine(" Configuration class.")

        buffer.Append("2    -- Use GetSection(string) to read ")
        buffer.AppendLine(" a custom section.")

        buffer.Append("3    -- Use SaveAs methods")
        buffer.AppendLine(" to save the configuration file.")

        buffer.Append("4    -- Use AppSettings property to read")
        buffer.AppendLine(" the appSettings section.")
        buffer.Append("5    -- Use ConnectionStrings property to read")
        buffer.AppendLine(" the connectionStrings section.")

        buffer.Append("6    -- Use Configuration class properties")
        buffer.AppendLine(" to obtain configuration information.")

        Console.Write(buffer.ToString())
    End Sub

    ' Obtain user's input and provide
    ' feedback.
    Shared Sub Main(ByVal args() As String)
        ' Define user selection string.
        Dim selection As String

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


        ' Get user selection.
        Do

            UserMenu()
            Console.Write("> ")
            selection = Console.ReadLine()
            If selection <> String.Empty Then
                Exit Do
            End If
        Loop

        Do While selection.ToLower() <> "q"
            ' Process user's input.
            Select Case selection
                Case "1"
                    ' Show how to create an instance of the Configuration class.
                    UsingConfigurationClass.CreateConfigurationFile()

                Case "2"
                    ' Show how to use GetSection(string) method.
                    UsingConfigurationClass.GetCustomSection()

                Case "3"
                    ' Show how to use ConnectionStrings.
                    UsingConfigurationClass.SaveConfigurationFile()

                Case "4"
                    ' Show how to use the AppSettings property.
                    UsingConfigurationClass.GetSections("appSettings")

                Case "5"
                    ' Show how to use the ConnectionStrings property.
                    UsingConfigurationClass.GetSections("connectionStrings")

                Case "6"
                    ' Show how to obtain configuration file information.
                    UsingConfigurationClass.GetConfigurationInformation()


                Case Else
                    UserMenu()
            End Select
            Console.Write("> ")
            selection = Console.ReadLine()
        Loop
    End Sub
End Class
#End Region

Комментарии

Параметры конфигурации хранятся в иерархии файлов конфигурации. Экземпляр Configuration класса представляет объединенное представление параметров конфигурации из всех файлов конфигурации, которые применяются к определенной физической сущности, например к компьютеру, или к логической сущности, такой как приложение или веб-сайт. Логическая сущность может существовать на локальном компьютере или на удаленном сервере. Сведения о файлах конфигурации см. в разделе Настройка приложений и файлов конфигурации ASP.NET.

Если для указанной сущности не существует файла конфигурации, Configuration объект представляет параметры конфигурации по умолчанию, определенные в файле Machine.config.

Объект можно получить Configuration с помощью следующих классов:

  • Класс ConfigurationManager , если ваша сущность является клиентским приложением.

  • Класс WebConfigurationManager , если ваша сущность является веб-приложением.

Имена методов, возвращающих объект, Configuration начинаются с "Открыть".

Можно также создать файл конфигурации, представляющий параметры конфигурации в объекте Configuration . Для этого используйте один из следующих методов:

  • Save Вызовите метод , чтобы создать новый файл конфигурации.

  • Вызовите метод , SaveAs чтобы создать новый файл конфигурации в другом расположении.

Имена методов, создающих файлы конфигурации, начинаются с "Сохранить".

Примечание

Чтобы включить доступ к параметрам конфигурации на удаленном компьютере, используйте программу командной строки Aspnet_regiis. Дополнительные сведения об этом средстве см . в разделе ASP.NET средство регистрации IIS (Aspnet_regiis.exe).. Сведения о создании пользовательских параметров конфигурации, отличных от встроенных разделов, включенных в платформа .NET Framework, и доступе к ней смConfigurationSection. в разделе .

Примечания для тех, кто наследует этот метод

Класс Configuration предоставляет программный доступ для редактирования файлов конфигурации. Вы используете один из методов Open, предоставляемых классом WebConfigurationManager для веб-приложений или классом ConfigurationManager для клиентских приложений. Эти методы возвращают Configuration объект , который, в свою очередь, предоставляет методы и свойства, обрабатывающие базовые файлы конфигурации. Вы можете получить доступ к этим файлам для чтения или записи сведений о конфигурации.

Для чтения сведений GetSection(String) о конфигурации GetSectionGroup(String) используется метод или метод . Обратите внимание, что пользователь или процесс, который выполняет чтение, должен иметь следующие разрешения:

  • Разрешение на чтение файла конфигурации на текущем уровне иерархии конфигурации.

  • Разрешения на чтение для всех родительских файлов конфигурации.

Если приложению требуется доступ только для чтения к собственной конфигурации, рекомендуется использовать перегрузки GetSection методов для веб-приложений. Для клиентского приложения используйте GetSection(String) метод .

Эти методы предоставляют доступ к кэшируемым значениям конфигурации для текущего приложения, которое имеет лучшую Configuration производительность, чем класс .

Примечание. Если используется статический GetSection метод, принимающий параметр path, параметр path должен ссылаться на приложение, в котором выполняется код. В противном случае параметр игнорируется и возвращаются сведения о конфигурации для текущего запущенного приложения.

Для записи сведений о конфигурации Save используется один из методов. Обратите внимание, что пользователь или процесс, который выполняет запись, должен иметь следующие разрешения:

  • Разрешение на запись в файл конфигурации и каталог на текущем уровне иерархии конфигурации.

  • Разрешения на чтение для всех файлов конфигурации.

Свойства

AppSettings

Получает раздел конфигурации из объекта AppSettingsSection, который применяется к указанному объекту Configuration.

AssemblyStringTransformer

Задает делегат функции, используемый для преобразования строк сборки в файлах конфигурации.

ConnectionStrings

Получает раздел конфигурации из объекта ConnectionStringsSection, который применяется к указанному объекту Configuration.

EvaluationContext

Возвращает объект ContextInformation для объекта Configuration.

FilePath

Получает физический путь к файлу конфигурации, представленному данным объектом Configuration.

HasFile

Получает значение, указывающее, существует ли файл для ресурса, представленного данным объектом Configuration.

Locations

Получает расположения, определенные в данном объекте Configuration.

NamespaceDeclared

Получает или устанавливает значение, указывающее, содержит ли файл конфигурации пространство имен XML.

RootSectionGroup

Получает корень ConfigurationSectionGroup для данного объекта Configuration.

SectionGroups

Получает коллекцию групп разделов, определенных данной конфигурацией.

Sections

Получает коллекцию разделов, определенную данным объектом Configuration.

TargetFramework

Возвращает или задает целевую версию .NET, если целевой является версия, более ранняя по сравнению с текущей.

TypeStringTransformer

Задает делегат функции, используемый для преобразования строк типа в файлах конфигурации.

Методы

Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object)
GetHashCode()

Служит хэш-функцией по умолчанию.

(Унаследовано от Object)
GetSection(String)

Возвращает указанный объект ConfigurationSection.

GetSectionGroup(String)

Получает указанный объект ConfigurationSectionGroup.

GetType()

Возвращает объект Type для текущего экземпляра.

(Унаследовано от Object)
MemberwiseClone()

Создает неполную копию текущего объекта Object.

(Унаследовано от Object)
Save()

Записывает параметры конфигурации, содержащиеся в данном объекте Configuration, в текущий файл конфигурации XML.

Save(ConfigurationSaveMode)

Записывает параметры конфигурации, содержащиеся в данном объекте Configuration, в текущий файл конфигурации XML.

Save(ConfigurationSaveMode, Boolean)

Записывает параметры конфигурации, содержащиеся в данном объекте Configuration, в текущий файл конфигурации XML.

SaveAs(String)

Записывает параметры конфигурации, содержащиеся в данном объекте Configuration, в указанный файл конфигурации XML.

SaveAs(String, ConfigurationSaveMode)

Записывает параметры конфигурации, содержащиеся в данном объекте Configuration, в указанный файл конфигурации XML.

SaveAs(String, ConfigurationSaveMode, Boolean)

Записывает параметры конфигурации, содержащиеся в данном объекте Configuration, в указанный файл конфигурации XML.

ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)

Применяется к

См. также раздел