英語で読む

次の方法で共有


Configuration クラス

定義

特定のコンピューター、アプリケーション、またはリソースに適用できる構成ファイルを表します。 このクラスは継承できません。

C#
public sealed class Configuration
継承
Configuration

次のコード例では、 クラスを使用 Configuration して構成ファイル要素にアクセスする方法を示します。

C#
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

}

注釈

構成設定は、構成ファイルの階層に格納されます。 クラス インスタンスは Configuration 、コンピューターなどの特定の物理エンティティ、またはアプリケーションや Web サイトなどの論理エンティティに適用されるすべての構成ファイルの構成設定のマージされたビューを表します。 論理エンティティは、ローカル コンピューターまたはリモート サーバーに存在できます。 構成ファイルの詳細については、「 Configuring Apps and ASP.NET Configuration Files」を参照してください。

指定したエンティティに構成ファイルが存在しない場合、 オブジェクトは Configuration 、Machine.config ファイルで定義されている既定の構成設定を表します。

オブジェクトは、次の Configuration クラスを使用して取得できます。

  • エンティティが ConfigurationManager クライアント アプリケーションの場合は、 クラス。

  • エンティティが WebConfigurationManager Web アプリケーションの場合は、 クラス。

オブジェクトを返す Configuration メソッドの名前は、"Open" で始まります。

オブジェクトの構成設定を表す構成ファイルを Configuration 生成することもできます。 そのためには、次のいずれかのメソッドを使用します。

  • メソッドを Save 呼び出して、新しい構成ファイルを作成します。

  • メソッドを SaveAs 呼び出して、別の場所に新しい構成ファイルを生成します。

構成ファイルを作成するメソッドの名前は、"Save" で始まります。

注意

リモート コンピューターで構成設定へのアクセスを有効にするには、Aspnet_regiis コマンドライン ツールを使用します。 このツールの詳細については、「 ASP.NET IIS 登録ツール (Aspnet_regiis.exe)」を参照してください。 .NET Framework に含まれる組み込みセクション以外のカスタム構成設定の作成とアクセスについては、 を ConfigurationSection参照してください。

注意 (継承者)

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

構成情報を GetSection(String) 読み取るために、 GetSectionGroup(String) メソッドまたは メソッドを使用します。 読み取りを行うユーザーまたはプロセスには、次のアクセス許可が必要です。

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

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

アプリケーションで独自の構成への読み取り専用アクセスが必要な場合は、Web アプリケーションのメソッド オーバーロードを GetSection 使用することをお勧めします。 クライアント アプリケーションの場合は、 メソッドを使用します GetSection(String)

これらのメソッドは、現在のアプリケーションのキャッシュされた構成値へのアクセスを提供します。これは、 クラスよりもパフォーマンスが Configuration 優れています。

注: path パラメーターを受け取る静的 GetSection メソッドを使用する場合、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, Boolean)

この Configuration オブジェクトに格納されている構成設定を、現在の XML 構成ファイルに書き込みます。

Save(ConfigurationSaveMode)

この Configuration オブジェクトに格納されている構成設定を、現在の XML 構成ファイルに書き込みます。

SaveAs(String, ConfigurationSaveMode, Boolean)

この Configuration オブジェクトに格納されている構成設定を、指定された XML 構成ファイルに書き込みます。

SaveAs(String, ConfigurationSaveMode)

この Configuration オブジェクトに格納されている構成設定を、指定された XML 構成ファイルに書き込みます。

SaveAs(String)

この Configuration オブジェクトに格納されている構成設定を、指定された XML 構成ファイルに書き込みます。

ToString()

現在のオブジェクトを表す文字列を返します。

(継承元 Object)

適用対象

製品 バージョン
.NET 8 (package-provided), 9 (package-provided), 10 (package-provided)
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0 (package-provided)
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10

こちらもご覧ください