구성 클래스 사용

업데이트: 2007년 11월

대부분의 구성 작업은 Configuration 클래스를 사용하여 수행됩니다. 이 클래스는 컴퓨터, .NET 클라이언트 응용 프로그램, ASP.NET 응용 프로그램, 웹 디렉터리 및 웹 디렉터리에 저장된 리소스의 구성을 나타냅니다.

ASP.NET 버전 2.0에서는 구성 섹션을 가져오는 WebConfigurationManager 개체의 메서드를 사용하여 Configuration 클래스의 인스턴스에 액세스할 수 있습니다. .NET Framework 클라이언트 응용 프로그램에서는 유사한 ConfigurationManager 개체를 사용할 수 있습니다. 구성 섹션마다 고유의 개체 형식이 있으며, 이러한 형식은 ASP.NET 구성 설정의 참조 항목에 있는 "요소 정보" 표에 섹션 처리기로 나열되어 있습니다. 예제를 보려면 방법: 프로그래밍 방식으로 ASP.NET 구성 설정 사용을 참조하십시오.

다음 단원에서는 여러 가지 시나리오에서 구성 클래스를 사용하는 방법에 대해 설명합니다. 구성 클래스에 대한 요약은 ASP.NET 구성 API 개요를 참조하십시오.

아래의 모든 예제에서는 먼저 System.Configuration.Configuration 클래스의 인스턴스를 만들어 비정적 Configuration.GetSectionConfiguration.GetSectionGroup 메서드를 사용합니다. 이를 통해 모든 응용 프로그램에서 구성 정보를 가져올 수 있습니다. 코드가 있는 응용 프로그램에서 구성 정보를 가져오려면 정적 GetSection 메서드를 사용하는 것이 처리 속도가 빠릅니다. 자세한 내용은 ASP.NET 구성 API 개요의 "로컬 및 원격 구성 설정 사용" 단원을 참조하십시오.

전역 구성 설정에 매핑되는 구성 개체 열기

전역 구성의 구성 파일을 열려면 응용 프로그램에서 WebConfigurationManager 클래스의 OpenMachineConfiguration 정적 메서드를 호출합니다. 다음 코드 예제에서 OpenMachineConfiguration 메서드는 .NET Framework 2.0의 Machine.config 파일에 해당하는 구성 개체를 열고 반환합니다. 이 오버로드된 메서드의 다른 버전을 사용하면 위치, 원격 서버 또는 사용자 정보를 지정할 수 있습니다.

' Obtains the machine configuration settings on the local machine.
Dim machineConfig As System.Configuration.Configuration
machineConfig = _
    System.Web.Configuration.WebConfigurationManager.OpenMachineConfiguration()
machineConfig.SaveAs("c:\machineConfig.xml")
         // Obtains the machine configuration settings on the local machine.
            System.Configuration.Configuration machineConfig = 
                System.Web.Configuration.WebConfigurationManager.OpenMachineConfiguration();
            machineConfig.SaveAs("c:\\machineConfig.xml");

구성 API는 버전별로 다릅니다. 그러므로 한 버전의 .NET Framework에 대한 Machine.config 파일을 다른 버전의 .NET Framework에 포함된 메서드를 사용하여 열 수 없습니다.

필요한 권한

컴퓨터 구성 파일을 열려면 실제 Machine.config 파일에 대한 읽기 권한이 응용 프로그램에 있어야 합니다. 컴퓨터 구성을 수정하려면 파일에 대한 쓰기 권한과 .NET Framework 구성 디렉터리에 대한 만들기 권한이 응용 프로그램에 있어야 합니다.

웹 응용 프로그램 구성 설정에 매핑되는 구성 개체 열기

웹 응용 프로그램의 구성 파일을 열려면 응용 프로그램에서 WebConfigurationManager 클래스의 OpenWebConfiguration 정적 메서드를 호출하고, 열려는 IIS(인터넷 정보 서비스) 가상 디렉터리의 상대 경로를 전달합니다.

경로 매개 변수 값은 필요한 구성이 들어 있는 디렉터리의 IIS 메타베이스 경로에서 가져올 수 있습니다. 예를 들어, IIS 메타베이스 경로가 W3SVC/1/Root/Temp인 경우 기본 사이트가 1이므로 경로는 /Temp입니다.

다음 코드 예제에서 OpenWebConfiguration 메서드는 기본 웹 사이트의 임시 웹 응용 프로그램에 해당하는 구성 개체를 열고 반환합니다. 이 구성 개체에는 Web.config 파일에서 로컬로 지정된 구성 설정과 Machine.config 파일까지 포함하는 부모 구성 파일에서 상속된 모든 설정이 들어 있습니다. 이 오버로드된 메서드의 다른 버전을 사용하면 웹 사이트, 위치, 원격 서버 및 사용자 정보를 지정할 수 있습니다.

' Obtains the configuration settings for a Web application.
Dim webConfig As System.Configuration.Configuration
webConfig = _
    System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Temp")
webConfig.SaveAs("c:\\webConfig.xml")
         // Obtains the configuration settings for a Web application.
            System.Configuration.Configuration webConfig =
                System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Temp");
            webConfig.SaveAs("c:\\webConfig.xml");

실제 Web.config 파일이 없는 경우에도 System.Configuration.Configuration 개체를 열 수 있습니다. 이 경우 반환된 구성은 전적으로 구성 파일 계층 구조에서 상속된 설정으로만 구성됩니다. 자세한 내용은 ASP.NET 구성 시나리오를 참조하십시오.

필요한 권한

웹 구성 파일을 열려면 실제 Web.config 파일과 계층 구조상의 모든 부모 파일에 대한 읽기 권한이 응용 프로그램에 있어야 합니다.

구성 파일의 섹션에 매핑되는 구성 개체 열기

섹션에서 구성 정보를 가져오려면 응용 프로그램에서 Configuration 클래스의 GetSectionGroup 비정적 메서드를 호출하고 섹션 이름을 전달합니다. 섹션 그룹에 포함된 섹션의 경우, 섹션의 XPath(system.web/anonymousIdentification)를 사용하거나 섹션 그룹에 처음으로 매핑된 구성 개체를 가져올 수 있습니다. 섹션 이름의 목록을 보려면 ASP.NET 구성 설정을 참조하십시오.

다음 코드 예제에서 OpenWebConfiguration 메서드는 기본 웹 사이트의 임시 웹 응용 프로그램에 해당하는 구성 개체를 열어 반환한 후 이 개체를 사용하여 system.web 섹션 그룹에 대한 참조를 가져옵니다. 그런 다음 이 참조를 사용하여 anonymousIdentification 섹션에 대한 참조를 가져옵니다.

' Obtains the configuration settings for the <anonymousIdentification> section.
Dim config As System.Configuration.Configuration
config = _
    System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Temp")
Dim systemWeb As System.Web.Configuration.SystemWebSectionGroup
systemWeb = config.GetSectionGroup("system.web")
Dim sectionConfig As System.Web.Configuration.AnonymousIdentificationSection
sectionConfig = systemWeb.AnonymousIdentification
Dim sb As New StringBuilder
sb.AppendLine("<anonymousIdentification> attributes:")
Dim props As System.Configuration.PropertyInformationCollection
props = sectionConfig.ElementInformation.Properties
For Each prop As System.Configuration.PropertyInformation In props
    sb.Append(prop.Name.ToString())
    sb.Append(" = ")
    sb.AppendLine(prop.Value.ToString())
Next
Console.WriteLine(sb.ToString())
         // Obtains the configuration settings for the <anonymousIdentification> section.
            System.Configuration.Configuration config =
                System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Temp");
            System.Web.Configuration.SystemWebSectionGroup systemWeb =
                config.GetSectionGroup("system.web") 
                as System.Web.Configuration.SystemWebSectionGroup;
            System.Web.Configuration.AnonymousIdentificationSection sectionConfig =
                systemWeb.AnonymousIdentification;
            if (null != sectionConfig)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("<anonymousIdentification> attributes:\r\n");
                System.Configuration.PropertyInformationCollection props =
                    sectionConfig.ElementInformation.Properties;
                foreach (System.Configuration.PropertyInformation prop in props)
                {
                    sb.AppendFormat("{0} = {1}\r\n", prop.Name.ToString(), prop.Value.ToString());
                }
                Console.WriteLine(sb.ToString());
            }

실제 Web.config 파일이 없는 경우에도 System.Configuration.Configuration 개체를 열 수 있습니다. 이 경우 반환된 구성은 전적으로 구성 파일 계층 구조에서 상속된 설정으로만 구성됩니다. 자세한 내용은 ASP.NET 구성 시나리오를 참조하십시오.

필요한 권한

웹 구성 파일의 섹션을 열려면 실제 Web.config 파일과 계층 구조상의 모든 부모 파일에 대한 읽기 권한이 응용 프로그램에 있어야 합니다. 관리 코드 응용 프로그램에는 시스템 섹션을 읽을 수 있는 권한이 있어야 합니다. 완전 신뢰 및 높은 신뢰 응용 프로그램에는 기본적으로 이러한 권한이 있습니다. 즉, 기본적으로 보통 및 낮은 신뢰 응용 프로그램에서는 구성 섹션을 읽을 수 없습니다.

원격 구성 설정에 매핑되는 구성 개체 열기

구성 API를 사용하여 원격 컴퓨터의 구성을 열 수 있습니다. API에서는 다른 컴퓨터의 컴퓨터 구성 파일이나 모든 IIS 응용 프로그램 또는 해당 자식 디렉터리의 응용 프로그램 구성 파일을 열 수 있습니다.

다른 컴퓨터의 컴퓨터 구성 파일을 열려면 응용 프로그램에서 OpenMachineConfiguration 정적 메서드를 호출하고 서버 이름을 전달합니다.

다른 컴퓨터의 Web.config 파일을 열려면 응용 프로그램에서 OpenWebConfiguration 정적 메서드를 호출하고 사이트를 기준으로 한 구성 개체의 상대 경로, 사이트 식별자 및 서버 이름을 전달합니다. 반환된 구성 개체에는 Web.config 파일에서 로컬로 지정된 구성 설정과 Machine.config 파일까지 포함하는 부모 구성 파일에서 상속된 모든 설정이 들어 있습니다.

서버 이름은 유효한 Windows 네트워킹 컴퓨터 이름입니다. 이 이름은 ASP.NET에서 특별히 처리되지 않고 운영 체제에 직접 전달됩니다.

다음 코드 예제에서는 컴퓨터 구성, 기본 사이트의 루트 구성 및 응용 프로그램 디렉터리의 웹 구성을 여는 방법을 보여 줍니다.

Dim userToken As IntPtr
userToken = System.Security.Principal.WindowsIdentity.GetCurrent().Token

' Obtains the machine configuration settings on a remote machine.
Dim remoteMachineConfig As System.Configuration.Configuration
remoteMachineConfig = _
    System.Web.Configuration.WebConfigurationManager.OpenMachineConfiguration( _
    Nothing, "JanetFi2", userToken)
remoteMachineConfig.SaveAs("c:\remoteMachineConfig.xml")

' Obtains the root Web configuration settings on a remote machine.
Dim remoteRootConfig As System.Configuration.Configuration
remoteRootConfig = _
    System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration( _
    Nothing, Nothing, Nothing, "JanetFi2", userToken)
remoteRootConfig.SaveAs("c:\remoteRootConfig.xml")

' Obtains the configuration settings for the 
' W3SVC/1/Root/Temp application on a remote machine.
Dim remoteWebConfig As System.Configuration.Configuration
remoteWebConfig = _
    System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration( _
    "/Temp", "1", Nothing, "JanetFi2", userToken)
remoteWebConfig.SaveAs("c:\\remoteWebConfig.xml")
         IntPtr userToken = System.Security.Principal.WindowsIdentity.GetCurrent().Token;

            // Obtains the machine configuration settings on a remote machine.
            System.Configuration.Configuration remoteMachineConfig =
                System.Web.Configuration.WebConfigurationManager.OpenMachineConfiguration
                (null, "ServerName", userToken);
            remoteMachineConfig.SaveAs("c:\\remoteMachineConfig.xml");

            // Obtains the root Web configuration settings on a remote machine.
            System.Configuration.Configuration remoteRootConfig =
                System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration
                (null, null, null, "ServerName", userToken);
            remoteRootConfig.SaveAs("c:\\remoteRootConfig.xml");

            // Obtains the configuration settings for the 
            // W3SVC/1/Root/Temp application on a remote machine.
            System.Configuration.Configuration remoteWebConfig =
                System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration
                ("/Temp", "1", null, "ServerName", userToken);
            remoteWebConfig.SaveAs("c:\\remoteWebConfig.xml");

필요한 권한

원격 컴퓨터의 구성 파일을 열려면 응용 프로그램이 원격 컴퓨터에 대한 관리 권한이 있어야 합니다. 이 요구 사항은 로컬에서 사용하는 경우의 요구 사항보다 제한적입니다. 로컬 구성 파일의 경우, 계층 구조상의 구성 파일에 대한 읽기 권한과 IIS 경로 확인을 위해 IIS 메타베이스에 대한 읽기 권한만 응용 프로그램에 있으면 됩니다.

원격 컴퓨터를 구성하기 전에 이 컴퓨터에서 "-config+" 매개 변수를 사용하여 Aspnet_regiis.exe 도구를 실행합니다. 자세한 내용은 ASP.NET IIS 등록 도구(Aspnet_regiis.exe)를 참조하십시오.

구성 설정 업데이트

열린 구성 개체를 업데이트하려면 응용 프로그램에서 구성 개체의 Save 또는 SaveAs 메서드를 호출합니다. 이러한 메서드는 해당 개체의 모든 구성 설정 변경 사항을 씁니다. 구성 파일이 필요한 위치에 없으면 새 구성 파일이 만들어집니다.

다음 코드 예제에서는 컴파일 섹션의 debug 특성을 true로 설정합니다.

' Updates the configuration settings for a Web application.
Dim updateWebConfig As System.Configuration.Configuration
updateWebConfig = _
    System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Temp")
Dim compilation As System.Web.Configuration.CompilationSection
compilation = _
    updateWebConfig.GetSection("system.web/compilation")
Console.WriteLine("Current <compilation> debug = {0}", compilation.Debug)
compilation.Debug = True
If Not compilation.SectionInformation.IsLocked Then
    updateWebConfig.Save()
    Console.WriteLine("New <compilation> debug = {0}", compilation.Debug)
Else
    Console.WriteLine("Could not save configuration.")
End If
         // Updates the configuration settings for a Web application.
            System.Configuration.Configuration updateWebConfig =
                System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Temp");
            System.Web.Configuration.CompilationSection compilation =
                updateWebConfig.GetSection("system.web/compilation") 
                as System.Web.Configuration.CompilationSection;
            Console.WriteLine("Current <compilation> debug = {0}", compilation.Debug);
            compilation.Debug = true;
            if (!compilation.SectionInformation.IsLocked)
            {
                updateWebConfig.Save();
                Console.WriteLine("New <compilation> debug = {0}", compilation.Debug);
            }
            else
            {
                Console.WriteLine("Could not save configuration.");
            }

현재 구성 데이터를 업데이트할 때 이를 잠글 수 있는 기능이 없습니다. 따라서 구성 API에서는 구성을 수정할 때 낙관적 동시성 모델을 사용합니다. 낙관적 동시성 모델에서는 두 응용 프로그램이 동일한 구성을 동시에 열 경우, 각각 구성 개체의 고유한 복사본을 가져옵니다. 응용 프로그램에서 구성 개체를 가져온 후 기본 구성 파일이 수정된 경우 응용 프로그램에서 Save 또는 SaveAs 메서드를 호출하여 구성을 수정하려고 하면 메서드에서 예외가 발생합니다. 구성을 업데이트하는 다른 응용 프로그램에 의해 또는 구성 API와 상관 없이 다른 파일 변경 사항에 의해 기본 파일이 수정되었을 수 있습니다.

필요한 권한

웹 구성을 수정하려면 응용 프로그램에 파일에 대한 쓰기 권한과 파일이 포함된 디렉터리에 대한 만들기 권한이 있어야 합니다.

참고 항목

개념

ASP.NET 구성 API 개요

기타 리소스

ASP.NET 구성 설정