Configuration Configuration Configuration Configuration Class

정의

특정 컴퓨터, 애플리케이션 또는 리소스에 적용할 수 있는 구성 파일을 나타냅니다.Represents a configuration file that is applicable to a particular computer, application, or resource. 이 클래스는 상속될 수 없습니다.This class cannot be inherited.

public ref class Configuration sealed
public sealed class Configuration
type Configuration = class
Public NotInheritable Class Configuration
상속
ConfigurationConfigurationConfigurationConfiguration

예제

다음 코드 예제를 사용 하는 방법에 설명 합니다 Configuration 액세스 구성 파일 요소 클래스입니다.The following code example demonstrates how to use the Configuration class to access configuration file elements.

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 settings are stored in a hierarchy of configuration files. Configuration 클래스 인스턴스를 사용 하는 컴퓨터와 같은 특정 물리적 엔터티 또는 애플리케이션 또는 웹 사이트와 같은 논리 엔터티에 적용 되는 구성 파일의 모든 구성 설정이 병합된 된 보기를 나타냅니다.The Configuration class instance represents the merged view of the configuration settings from all of the configuration files that apply to a specific physical entity, such as a computer, or to a logical entity, such as an application or a Web site. 논리 엔터티 원격 서버에서 로컬 컴퓨터에 있을 수 있습니다.The logical entity can exist on the local computer or on a remote server. 구성 파일에 대 한 자세한 내용은 앱 구성 하 고 ASP.NET 구성 파일합니다.For information about configuration files, see Configuring Apps and ASP.NET Configuration Files.

지정 된 엔터티에 대 한 구성 파일이 없으면를 Configuration 개체 합니다 Machine.config 파일에 정의 된 대로 기본 구성 설정을 나타냅니다.When no configuration file exists for a specified entity, the Configuration object represents the default configuration settings as defined by the Machine.config file.

가져올 수 있습니다는 Configuration 다음 클래스를 사용 하 여 개체:You can get a Configuration object by using the following classes:

반환 하는 메서드 이름에는 Configuration 개체 "열기"로 시작 합니다.The names of the methods that return a Configuration object begin with "Open".

구성 설정을 나타내는 구성 파일을 생성할 수도 있습니다는 Configuration 개체입니다.You can also generate a configuration file that represents the configuration settings in a Configuration object. 이렇게 하려면 다음 메서드 중 하나를 사용합니다.To do this, use one of the following methods:

  • 호출 된 Save 메서드를 새 구성 파일을 만듭니다.Call the Save method to create a new configuration file.

  • 호출 된 SaveAs 다른 위치에 새 구성 파일을 생성 하는 방법입니다.Call the SaveAs method to generate a new configuration file at another location.

구성 파일을 만드는 방법의 이름은 "저장"을 사용 하 여 시작 합니다.The names of the methods that create configuration files begin with "Save".

참고

원격 컴퓨터에서 구성 설정에 대 한 액세스를 사용 하도록 설정 하려면 Aspnet_regiis 명령줄 도구를 사용 합니다.To enable access to configuration settings on a remote computer, use the Aspnet_regiis command-line tool. 이 도구에 대 한 자세한 내용은 참조 하세요. ASP.NET IIS Registration Tool (Aspnet_regiis.exe)합니다.For more information about this tool, see ASP.NET IIS Registration Tool (Aspnet_regiis.exe). 만들기 및.NET Framework에 포함 된 내장 섹션 이외의 사용자 지정 구성 설정에 액세스 하는 방법에 대 한 내용은 참조 ConfigurationSection합니다.For information about creating and accessing custom configuration settings other than the intrinsic sections included in the .NET Framework, refer to ConfigurationSection.

상속자 참고

Configuration 클래스는 구성 파일 편집에 대 한 프로그래밍 방식의 액세스를 제공 합니다.The Configuration class provides programmatic access for editing configuration files. 제공 하는 "열린" 메서드 중 하나를 사용 합니다 WebConfigurationManager 또는 웹 애플리케이션에 대 한 클래스는 ConfigurationManager 클라이언트 애플리케이션에 대 한 클래스입니다.You use one of the "Open" methods provided by the WebConfigurationManager class for Web applications or by the ConfigurationManager class for client applications. 이러한 메서드는 반환을 Configuration 에 기본 구성 파일을 처리 하는 속성과 메서드를 제공 하는 개체입니다.These methods return a Configuration object, which in turn provides the methods and properties that handle the underlying configuration files. 이러한 파일을 읽기용 또는 쓰기용 구성 정보를 액세스할 수 있습니다.You can access these files for reading or writing configuration information.

사용 된 GetSection(String) 메서드 또는 GetSectionGroup(String) 구성 정보를 읽어야 하는 방법입니다.You use the GetSection(String) method or the GetSectionGroup(String) method to read configuration information. Note 사용자나 읽는 프로세스는 다음 권한이 있어야 합니다.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.

애플리케이션에서 자체 구성에 대 한 읽기 전용 액세스에 필요한 것이 좋습니다 사용 하 여 GetSection 웹 애플리케이션에 대 한 메서드 오버 로드 합니다.If your application needs read-only access to its own configuration, it is recommended that you use the GetSection method overloads for Web applications. 클라이언트 애플리케이션에 사용 된 GetSection(String) 메서드.For client application, use the GetSection(String) method.

이러한 메서드에 액세스할 수 있는 보다 더 나은 성능을 현재 애플리케이션에 대 한 캐시 된 구성 값에는 Configuration 클래스입니다.These methods provide access to the cached configuration values for the current application, which has better performance than the Configuration class.

정적을 사용 하는 경우 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.

하나를 사용 하 여 Save 구성 정보를 기록 하는 방법.You use one of the Save methods to write configuration information. Note는 사용자 또는 기록 하는 프로세스는 다음 권한이 있어야 합니다.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.

속성

AppSettings AppSettings AppSettings AppSettings

가져옵니다 합니다 AppSettingsSection 이 적용 되는 개체 구성 섹션 Configuration 개체입니다.Gets the AppSettingsSection object configuration section that applies to this Configuration object.

AssemblyStringTransformer AssemblyStringTransformer AssemblyStringTransformer AssemblyStringTransformer

구성 파일의 어셈블리 문자열을 변환 하는 데 사용 되는 함수 대리자를 지정 합니다.Specifies a function delegate that is used to transform assembly strings in configuration files.

ConnectionStrings ConnectionStrings ConnectionStrings ConnectionStrings

가져옵니다를 ConnectionStringsSection 이 적용 되는 구성 섹션 개체 Configuration 개체입니다.Gets a ConnectionStringsSection configuration-section object that applies to this Configuration object.

EvaluationContext EvaluationContext EvaluationContext EvaluationContext

ContextInformation 개체에 대한 Configuration 개체를 가져옵니다.Gets the ContextInformation object for the Configuration object.

FilePath FilePath FilePath FilePath

이 나타내는 구성 파일에 실제 경로 가져옵니다 Configuration 개체입니다.Gets the physical path to the configuration file represented by this Configuration object.

HasFile HasFile HasFile HasFile

이 표시 되는 리소스에 대 한 파일이 있는지 여부를 나타내는 값을 가져옵니다 Configuration 개체입니다.Gets a value that indicates whether a file exists for the resource represented by this Configuration object.

Locations Locations Locations Locations

내에 정의 된 위치를 가져옵니다 Configuration 개체입니다.Gets the locations defined within this Configuration object.

NamespaceDeclared NamespaceDeclared NamespaceDeclared NamespaceDeclared

구성 파일에 XML 네임 스페이스에 있는지 여부를 나타내는 값을 가져오거나 설정 합니다.Gets or sets a value indicating whether the configuration file has an XML namespace.

RootSectionGroup RootSectionGroup RootSectionGroup RootSectionGroup

루트를 가져옵니다 ConfigurationSectionGroupConfiguration 개체입니다.Gets the root ConfigurationSectionGroup for this Configuration object.

SectionGroups SectionGroups SectionGroups SectionGroups

이 구성에서 정의 하는 섹션 그룹의 컬렉션을 가져옵니다.Gets a collection of the section groups defined by this configuration.

Sections Sections Sections Sections

이 정의 된 섹션의 컬렉션을 가져옵니다 Configuration 개체입니다.Gets a collection of the sections defined by this Configuration object.

TargetFramework TargetFramework TargetFramework TargetFramework

버전을 이전 보다 현재 대상으로 하는 경우.NET Framework의 대상된 버전을 지정 합니다.Specifies the targeted version of the .NET Framework when a version earlier than the current one is targeted.

TypeStringTransformer TypeStringTransformer TypeStringTransformer TypeStringTransformer

구성 파일의 형식 문자열을 변환 하는 데 사용 되는 함수 대리자를 지정 합니다.Specifies a function delegate that is used to transform type strings in configuration files.

메서드

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

지정한 개체와 현재 개체가 같은지 여부를 확인합니다.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

기본 해시 함수로 작동합니다.Serves as the default hash function.

(Inherited from Object)
GetSection(String) GetSection(String) GetSection(String) GetSection(String)

지정된 ConfigurationSection 개체를 반환합니다.Returns the specified ConfigurationSection object.

GetSectionGroup(String) GetSectionGroup(String) GetSectionGroup(String) GetSectionGroup(String)

지정 된 가져옵니다 ConfigurationSectionGroup 개체입니다.Gets the specified ConfigurationSectionGroup object.

GetType() GetType() GetType() GetType()

현재 인스턴스의 Type을 가져옵니다.Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.Creates a shallow copy of the current Object.

(Inherited from Object)
Save() Save() Save() Save()

이 포함 된 구성 설정을 기록 Configuration 현재 XML 구성 파일에는 개체입니다.Writes the configuration settings contained within this Configuration object to the current XML configuration file.

Save(ConfigurationSaveMode) Save(ConfigurationSaveMode) Save(ConfigurationSaveMode) Save(ConfigurationSaveMode)

이 포함 된 구성 설정을 기록 Configuration 현재 XML 구성 파일에는 개체입니다.Writes the configuration settings contained within this Configuration object to the current XML configuration file.

Save(ConfigurationSaveMode, Boolean) Save(ConfigurationSaveMode, Boolean) Save(ConfigurationSaveMode, Boolean) Save(ConfigurationSaveMode, Boolean)

이 포함 된 구성 설정을 기록 Configuration 현재 XML 구성 파일에는 개체입니다.Writes the configuration settings contained within this Configuration object to the current XML configuration file.

SaveAs(String) SaveAs(String) SaveAs(String) SaveAs(String)

이 포함 된 구성 설정을 기록 Configuration 지정된 된 XML 구성 파일에는 개체입니다.Writes the configuration settings contained within this Configuration object to the specified XML configuration file.

SaveAs(String, ConfigurationSaveMode) SaveAs(String, ConfigurationSaveMode) SaveAs(String, ConfigurationSaveMode) SaveAs(String, ConfigurationSaveMode)

이 포함 된 구성 설정을 기록 Configuration 지정된 된 XML 구성 파일에는 개체입니다.Writes the configuration settings contained within this Configuration object to the specified XML configuration file.

SaveAs(String, ConfigurationSaveMode, Boolean) SaveAs(String, ConfigurationSaveMode, Boolean) SaveAs(String, ConfigurationSaveMode, Boolean) SaveAs(String, ConfigurationSaveMode, Boolean)

이 포함 된 구성 설정을 기록 Configuration 지정된 된 XML 구성 파일에는 개체입니다.Writes the configuration settings contained within this Configuration object to the specified XML configuration file.

ToString() ToString() ToString() ToString()

현재 개체를 나타내는 문자열을 반환합니다.Returns a string that represents the current object.

(Inherited from Object)

적용 대상

추가 정보