構成クラスの使用

更新 : 2007 年 11 月

構成作業のほとんどは Configuration クラスを使用して行います。このクラスは、コンピュータ、.NET クライアント アプリケーション、ASP.NET アプリケーション、Web ディレクトリ、および Web ディレクトリ内に格納されるリソースの各構成を表します。

ASP.NET Version 2.0 では、WebConfigurationManager オブジェクトの、構成セクションを取得するメソッドを使用して、Configuration クラスのインスタンスにアクセスできます (.NET Framework クライアント アプリケーションでは、上記のオブジェクトに似た ConfigurationManager オブジェクトを使用します)。各構成セクションごとにオブジェクトの型があり、これは「ASP.NET 構成設定」の参照トピック内の "要素情報" の表に、セクション ハンドラとして一覧表示されています。カスタマイズ例については、「方法 : プログラムによって ASP.NET 構成設定にアクセスする」を参照してください。

次のセクションでは、さまざまなシナリオでの構成クラスの使い方を説明します。構成クラスの概要については、「ASP.NET 構成 API の概要」を参照してください。

以下のすべての例では、非静的な Configuration.GetSection メソッドと Configuration.GetSectionGroup メソッドが使用されていますが、そのために、最初に System.Configuration.Configuration クラスのインスタンスが作成されます。これにより、任意のアプリケーションから構成情報を取得できます。コードが存在するアプリケーションから構成情報を取得する場合は、処理のより高速な 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 構成ディレクトリに対する作成許可が必要です。

Web アプリケーション構成設定にマップされた構成オブジェクトを開く

Web アプリケーションの構成ファイルを開くには、アプリケーションから WebConfigurationManager クラスの OpenWebConfiguration 静的メソッドを呼び出し、開く対象のインターネット インフォメーション サービス (IIS) 仮想ディレクトリの相対パスを渡します。

パスのパラメータ値は、必須構成を格納したディレクトリの IIS メタベース パスから取得できます。たとえば、IIS メタベース パスが W3SVC/1/Root/Temp であれば、既定のサイトは 1 であるためパスは /Temp になります。

次のコード例では、OpenWebConfiguration メソッドにより、既定の Web サイトの Temp Web アプリケーションに対応する構成オブジェクトが開かれ、返されます。この構成オブジェクトには、Web.config ファイルでローカルに指定された構成設定と、親構成ファイルから Machine.config ファイルまでのすべてのファイルから継承された設定がすべて格納されています。オーバーロードされたこのメソッドの別のバージョンでは、Web サイト、場所、リモート サーバー、およびユーザー情報を指定できます。

' 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 構成ファイルを開くには、アプリケーションに Web.config 物理ファイルおよび階層内のすべての親ファイルに対する読み取りアクセス許可が必要です。

構成ファイルのセクションにマップされた構成オブジェクトを開く

セクションから構成情報を取得するには、アプリケーションから Configuration クラスの GetSectionGroup 非静的メソッドを呼び出し、セクション名を渡します。セクション グループ内のセクションについては、セクションの XPath (system.web/anonymousIdentification) を使用するか、最初にセクション グループにマップされた構成オブジェクトを取得します。セクション名の一覧については、「ASP.NET 構成設定」を参照してください。

次のコード例では、OpenWebConfiguration メソッドにより、既定の Web サイトの Temp Web アプリケーションに対応する構成オブジェクトが開かれて返され、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 構成ファイルのセクションを開くには、アプリケーションに Web.config 物理ファイルおよび階層内のすべての親ファイルに対する読み取りアクセス許可が必要です。マネージ コード アプリケーションには、システムのセクションを読み取るアクセス許可が必要です。完全に信頼されているアプリケーションおよび信頼性の高いアプリケーションには、既定でこれらのアクセス許可が与えられています。つまり、既定では信頼性が中以下のアプリケーションは、構成セクションを読み取ることができません。

リモート構成設定にマップされた構成オブジェクトを開く

リモート コンピュータの構成を開く場合は、構成 API を使用します。API を使用すると、別のコンピュータのマシン構成ファイルや、IIS アプリケーションのアプリケーション構成ファイルまたはその子ディレクトリを開くことができます。

別のコンピュータでマシン構成ファイルを開くには、アプリケーションから OpenMachineConfiguration 静的メソッドを呼び出し、サーバー名を渡します。

別のコンピュータ上の Web.config ファイルを開くには、アプリケーションから OpenWebConfiguration 静的メソッドを呼び出し、構成オブジェクトへのサイト相対パス、サイト ID、およびサーバー名を渡します。返された構成オブジェクトには、Web.config ファイルでローカルに指定された構成設定と、親構成ファイルから Machine.config ファイルまでのすべてのファイルから継承された設定がすべて格納されています。

サーバー名は、有効な Windows ネットワーク コンピュータ名になります。この名前は ASP.NET で特に処理されることなく、オペレーティング システムに直接渡されます。

マシン構成、既定サイトのルート構成、およびアプリケーション ディレクトリの Web 構成を開く方法を次のコード例に示します。

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 メソッドを呼び出します。これらのメソッドは、構成オブジェクトの構成設定に変更があった場合、その変更を書き込みます。構成ファイルがその場所に存在しない場合、新しい構成ファイルが作成されます。

次のコード例では、compilation セクションの 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 は構成の変更について、オプティミスティック同時実行制御モデルを使用します。オプティミスティック同時実行制御モデルの下では、2 つのアプリケーションが同時に同じ構成を開いた場合、構成オブジェクトから個別にコピーを取得します。アプリケーションが Save メソッドまたは SaveAs メソッドを呼び出して構成を変更しようと試み、アプリケーションが構成オブジェクトを取得した後で基になる構成ファイルが変更されている場合、メソッドにより例外が発生します。基になるファイルは、別のアプリケーションによる構成の更新、または構成 API 以外によるファイルへの変更によって変更されている可能性があります。

必須許可

Web 構成を変更するには、アプリケーションに、ファイル対する書き込みアクセス許可と、ファイルを格納するディレクトリに対する作成許可が必要です。

参照

概念

ASP.NET 構成 API の概要

その他の技術情報

ASP.NET 構成設定