System.Configuration 名前空間


.NET Framework クラス ライブラリ
ConfigurationManager クラス

更新 : 2007 年 11 月

クライアント アプリケーションの構成ファイルにアクセスできるようにします。このクラスは継承できません。

名前空間 :  System.Configuration
アセンブリ :  System.Configuration (System.Configuration.dll 内)

構文

Visual Basic (宣言)
Public NotInheritable Class ConfigurationManager
Visual Basic (使用法)
メンバにアクセスするために、静的クラスのインスタンスを宣言する必要はありません。
C#
public static class ConfigurationManager
Visual C++
public ref class ConfigurationManager abstract sealed
J#
public final class ConfigurationManager
JScript
public final class ConfigurationManager
解説

ConfigurationManager クラスを使用すると、マシン構成情報、アプリケーション構成情報、およびユーザー構成情報にアクセスできます。このクラスは ConfigurationSettings クラスに代わるもので、優先して使用されます。

メモ :

アプリケーションのホストによって異なるアプリケーション構成ファイルの名前と場所。詳細については、「アプリケーション構成ファイル」を参照してください。

System.Configuration の組み込みの型またはこれらの型から派生した型を使用して、構成情報を処理できます。これらの型を使用すると、構成情報を直接処理することが可能で、構成ファイルを拡張してカスタム情報を含めることもできます。

ConfigurationManager クラスには、次のタスクを実行できるメンバが含まれています。

  • 構成ファイルからセクションを読み取ります。構成情報にアクセスするには、GetSection メソッドを呼び出します。appSettingsconnectionStrings などの一部のセクションには、AppSettings クラスおよび ConnectionStrings クラスを使用します。これらのメンバは、読み取り専用の操作を実行し、構成のキャッシュされた 1 つのインスタンスを使用し、マルチスレッド対応です。

  • 構成ファイル全体の読み取りと書き込みを行います。アプリケーションは、そのアプリケーション自体や他のアプリケーション、またはコンピュータのあらゆるレベルで、ローカルまたはリモートから構成設定の読み取りと書き込みを行うことができます。ConfigurationManager クラスに用意されているメソッドのいずれかを使用して、SampleApp.exe.config などの構成ファイルを開くことができます。これらのメソッドは、Configuration オブジェクトを返します。このオブジェクトは、関連付けられている構成ファイルの処理に使用できるメソッドとプロパティを公開します。メソッドは、読み取り操作または書き込み操作を実行し、ファイルに書き込みが行われるたびに構成データを作成します。

  • 構成タスクをサポートします。次の型を使用して、さまざまな構成タスクをサポートします。

    既存の構成情報の処理に加え、ConfigurationElementConfigurationElementCollectionConfigurationPropertyConfigurationSection の各クラスなど、組み込みの構成の種類を拡張することによって、カスタム構成要素を作成し使用できます。組み込みの構成の種類をプログラムによって拡張する方法の例については、ConfigurationSection に関するトピックを参照してください。属性ベースのモデルを使用する、組み込みの構成の種類を拡張する方法の例については、ConfigurationElement に関するトピックを参照してください。

実装元へのメモ :

Configuration クラスは、構成ファイルの編集をプログラムから行うことができるようにします。ConfigurationManager によって提供された、Open メソッドの 1 つを使用します。これらのメソッドは、Configuration オブジェクトを返します。このオブジェクトにより、基になる構成ファイルを処理するために必要なメソッドとプロパティが提供されます。これらのファイルへの読み取りアクセスまたは書き込みアクセスができます。

構成ファイルを読み取るには、GetSection または GetSectionGroup を使用して構成情報を読み取ります。読み取りを行うユーザーまたはプロセスに、次のアクセス許可が必要です。

  • 現在の構成階層レベルの構成ファイルに対する読み取りアクセス許可。

  • すべての親構成ファイルに対する読み取りアクセス許可。

アプリケーションが独自の構成に対する読み取り専用アクセスを行う必要がある場合は、GetSection メソッドを使用することをお勧めします。これらのメソッドにより、現在のアプリケーションのキャッシュされた構成値にアクセスできます。こちらの方が、Configuration クラスよりもパフォーマンスが優れています。

構成ファイルへの書き込みを行うには、Save メソッドのいずれかを使用します。書き込みを行うユーザーまたはプロセスに、次のアクセス許可が必要です。

  • 現在の構成階層レベルの構成ファイルおよびディレクトリに対する書き込みアクセス許可。

  • すべての構成ファイルに対する読み取りアクセス許可。


コンソール アプリケーションで ConfigurationManager クラスを使用する方法を次の例に示します。コードを次に示します。

  • appSettings 構成セクションにアクセスする方法。セクションが存在しない場合は、セクションが作成され、構成ファイルに追加されます。アプリケーション構成ファイルが存在しない場合は、作成されます。

  • Machine.config ファイルにアクセスし、既定の接続文字列 (定義されている場合) および現在構成しているセクションなどの情報を取得する方法。

    メモ :

    プロジェクトを作成する場合は、System.Configuration アセンブリへの参照を追加します。このアセンブリには、ConfigurationManager クラスが含まれます。

Visual Basic
Imports System
Imports System.Collections.Specialized
Imports System.Collections.ObjectModel
Imports System.Collections
Imports System.Text
Imports System.Configuration

Class UsingConfigurationManager


    ' Show how to use AppSettings.
    Shared Sub DisplayAppSettings()

        ' Get the AppSettings collection.
        Dim appSettings As NameValueCollection = _
        ConfigurationManager.AppSettings

        Dim keys As String() = appSettings.AllKeys

        Console.WriteLine()
        Console.WriteLine("Application appSettings:")

        ' Loop to get key/value pairs.
        Dim i As Integer
        For i = 0 To appSettings.Count - 1
            Console.WriteLine("#{0} Name: {1} Value: {2}", i, _
            keys(i), appSettings(i))
        Next i

    End Sub 'DisplayAppSettings

    ' Show how to use ConnectionStrings.
    ' This sub assumes that at least one connection string
    ' has been defined.
    Shared Sub DisplayConnectionStrings()

        ' Get the ConnectionStrings collection.
        Dim connections As ConnectionStringSettingsCollection = _
        ConfigurationManager.ConnectionStrings

        If connections.Count <> 0 Then
            Console.WriteLine("Connection strings:")
            ' Loop to get the collection elements.
            For Each connection As ConnectionStringSettings In connections
                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
        Else
            Console.WriteLine("No connection string is defined.")
        End If

    End Sub 'DisplayConnectionStrings

    ' Show how to use OpenMachineConfiguration.
    Shared Sub DisplayMachineConfigSections()
        ' Get the machine.config file.
        Dim machineConfig As Configuration = _
        ConfigurationManager.OpenMachineConfiguration()

        Dim sections As ConfigurationSectionCollection = _
        machineConfig.Sections

        Console.WriteLine()
        Console.WriteLine("Sections in machine.config:")

        ' Loop to get the sections machine.config.
        Dim section As ConfigurationSection
        For Each section In sections
            Dim name As String = section.SectionInformation.Name
            Console.WriteLine("Name: {0}", name)
        Next section

    End Sub 'DisplayMachineConfigSections


    ' Show how to use OpenExeConfiguration(ConfigurationUserLevel) 
    ' and RefreshSection. 
    ' This function creates a configuration file for the application, if one
    ' does not exist.
    Shared Sub UpdateAppSettings()
        ' Get the configuration file.
        Dim config As System.Configuration.Configuration = _
        ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)

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

        Dim newValue As String = DateTime.Now.ToLongDateString() + " " + _
        DateTime.Now.ToLongTimeString()

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

        ' Save the configuration file.
        config.Save(ConfigurationSaveMode.Modified)

        ' Force a reload of the changed section.
        ConfigurationManager.RefreshSection("appSettings")

    End Sub 'UpdateAppSettings

    ' Show how to use OpenExeConfiguration(string).
    Shared Sub DisplayAppSettingsRawXml()


        ' Get the application path.
        Dim exePath As String = System.IO.Path.Combine( _
        Environment.CurrentDirectory, "ConfigurationManager.exe")

        ' Get the configuration file.
        Dim config As System.Configuration.Configuration = _
        ConfigurationManager.OpenExeConfiguration(exePath)

        ' Get the AppSetins section.
        Dim appSettingSection As AppSettingsSection = _
        config.AppSettings

        ' Display raw xml.
        Console.WriteLine( _
        appSettingSection.SectionInformation.GetRawXml())

    End Sub 'DisplayAppSettingsRawXml


    ' Show how to use GetSection.
    Shared Sub DisplayAppSettingsSectionRawXml()

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

        ' Get the AppSetins section.
        Dim appSettingSection As AppSettingsSection = _
        CType(config.GetSection("appSettings"), AppSettingsSection)

        ' Display raw xml.
        Console.WriteLine("appSettings XML:")
        Console.WriteLine(appSettingSection.SectionInformation.GetRawXml())

    End Sub 'DisplayAppSettingsSectionRawXml


    ' Show how to use OpenMappedMachineConfiguration.
    Shared Sub DisplayMappedMachineConfigurationFileSections()
        ' Get the machine.config file.
        Dim machineConfig As Configuration = _
        ConfigurationManager.OpenMachineConfiguration()

        ' Map to the machine configuration file.
        Dim configFile As New ConfigurationFileMap(machineConfig.FilePath)
        Dim config As Configuration = _
        ConfigurationManager.OpenMappedMachineConfiguration(configFile)

        ' Display the configuration file sections.
        Dim sections As ConfigurationSectionCollection = config.Sections

        Console.WriteLine()
        Console.WriteLine("Sections in machine.config:")

        ' Loop to get the sections machine.config.
        Dim section As ConfigurationSection
        For Each section In sections
            Dim name As String = section.SectionInformation.Name
            Console.WriteLine("Name: {0}", name)
        Next section

    End Sub 'DisplayMappedMachineConfigurationFileSections


    ' Show how to use OpenMappedExeConfiguration.
    Shared Sub DisplayMappedExeConfigurationFileSections()
        ' Get the application configuration file path.
        Dim exeFilePath As String = System.IO.Path.Combine( _
        Environment.CurrentDirectory, "ConfigurationManager.exe.config")

        ' Map to the application configuration file.
        Dim configFile As New ExeConfigurationFileMap()
        configFile.ExeConfigFilename = exeFilePath
        Dim config As Configuration = _
        ConfigurationManager.OpenMappedExeConfiguration(configFile, _
        ConfigurationUserLevel.None)

        ' Display the configuration file sections.
        Dim sections As ConfigurationSectionCollection = config.Sections

        Console.WriteLine()
        Console.WriteLine("Sections in machine.config:")

        ' Loop to get the sections machine.config.
        Dim section As ConfigurationSection
        For Each section In sections
            Dim name As String = section.SectionInformation.Name
            Console.WriteLine("Name: {0}", name)
        Next section

    End Sub 'DisplayMappedExeConfigurationFileSections

    Shared Sub Main(ByVal args() As String)

        ' Show how to use OpenExeConfiguration() and RefreshSection.
        UpdateAppSettings()

        ' Show how to use AppSettings.
        DisplayAppSettings()

        ' Show how to use OpenExeConfiguration(string).
        DisplayAppSettingsRawXml()

        ' Show how to use GetSection.
        DisplayAppSettingsSectionRawXml()

        ' Show how to use ConnectionStrings.
        DisplayConnectionStrings()

        ' Show how to use OpenMappedMachineConfiguration.
        DisplayMappedMachineConfigurationFileSections()

        ' Show how to use OpenMappedExeConfiguration.
        DisplayMappedExeConfigurationFileSections()

        ' Show how to use OpenMachineConfiguration.
        DisplayMachineConfigSections()

    End Sub 'Main 
End Class 'UsingConfigurationManager

この例では、次の構成ファイルに示されるような要素を処理します。これらの要素は、この例を初めて実行したときに生成されます。

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="NewKey0" value="Monday, January 23, 2006 2:56:14 PM" />
  </appSettings>
</configuration>
継承階層

System..::.Object
  System.Configuration..::.ConfigurationManager
スレッド セーフ

この型のすべてのパブリック static (Visual Basic では Shared) メンバは、スレッド セーフです。インスタンス メンバの場合は、スレッド セーフであるとは限りません。
プラットフォーム

Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

.NET Framework および .NET Compact Framework では、各プラットフォームのすべてのバージョンはサポートしていません。サポートされているバージョンについては、「.NET Framework システム要件」を参照してください。

バージョン情報

.NET Framework

サポート対象 : 3.5、3.0、2.0
参照

参照

その他の技術情報

タグ :


Page view tracker