英語で読む

次の方法で共有


ConfigurationElement クラス

定義

構成ファイル内の構成要素を表します。

C#
public abstract class ConfigurationElement
継承
ConfigurationElement
派生

次のコード例は、カスタム セクションの個々の要素として、およびカスタム ConfigurationElement セクションの要素のコレクションとしてカスタムを実装する方法を示しています。 この例は、次のファイルで構成されています。

  • という名前 MyUrlsのカスタム セクションを含む app.config ファイル。 このセクションには、単純な要素 (他の要素は含まれません) と要素のコレクションが含まれています。 simple 要素には という名前 simple が付けられ、コレクションには という名前が付けられます urls

  • コンソール アプリケーション。 アプリケーションは、app.config ファイルの内容を読み取り、コンソールに情報を書き込みます。 、、および からConfigurationElementConfigurationElementCollection派生したクラスを使用しますConfigurationSection

  • クラスから派生する という名前 UrlsSectionConfigurationSection クラス。 このクラスは、構成ファイルの MyUrls セクションにアクセスするために使用されます。

  • クラスから派生する という名前 UrlsCollectionConfigurationElementCollection クラス。 このクラスは、構成ファイル内の urls コレクションにアクセスするために使用されます。

  • クラスから派生する という名前 UrlConfigElementConfigurationElement クラス。 このクラスは、構成ファイル内の simple 要素とコレクションのメンバーに urls アクセスするために使用されます。

この例を実行するには、次の手順を実行します。

  1. コンソール アプリケーション プロジェクトと という名前 ConfigurationElementのクラス ライブラリ プロジェクトを含むソリューションを作成します。

  2. クラス ライブラリ プロジェクトに 3 つのクラス ファイルを配置し、コンソール ライブラリ プロジェクトに他のファイルを配置します。

  3. 両方のプロジェクトで、 への参照 System.Configurationを設定します。

  4. コンソール アプリケーション プロジェクトで、プロジェクト参照をクラス ライブラリ プロジェクトに設定します。

C#
// Set Assembly name to ConfigurationElement
using System;
using System.Configuration;
using System.Collections;

namespace Samples.AspNet
{
    // Entry point for console application that reads the 
    // app.config file and writes to the console the 
    // URLs in the custom section.  
    class TestConfigurationElement
    {
        static void Main(string[] args)
        {
            // Get current configuration file.
            System.Configuration.Configuration config =
                ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None);

            // Get the MyUrls section.
            UrlsSection myUrlsSection =
                config.GetSection("MyUrls") as UrlsSection;

            if (myUrlsSection == null)
            {
                Console.WriteLine("Failed to load UrlsSection.");
            }
            else
            {
                Console.WriteLine("The 'simple' element of app.config:");
                Console.WriteLine("  Name={0} URL={1} Port={2}",
                    myUrlsSection.Simple.Name,
                    myUrlsSection.Simple.Url,
                    myUrlsSection.Simple.Port);

                Console.WriteLine("The urls collection of app.config:");
                for (int i = 0; i < myUrlsSection.Urls.Count; i++)
                {
                    Console.WriteLine("  Name={0} URL={1} Port={2}",
                        myUrlsSection.Urls[i].Name,
                        myUrlsSection.Urls[i].Url,
                        myUrlsSection.Urls[i].Port);
                }
            }
            Console.ReadLine();
        }
    }
}
C#
using System;
using System.Configuration;
using System.Collections;

namespace Samples.AspNet
{
    // Define a custom section containing an individual
    // element and a collection of elements.
    public class UrlsSection : ConfigurationSection
    {
        [ConfigurationProperty("name", 
            DefaultValue = "MyFavorites",
            IsRequired = true, 
            IsKey = false)]
        [StringValidator(InvalidCharacters = 
            " ~!@#$%^&*()[]{}/;'\"|\\",
            MinLength = 1, MaxLength = 60)]
        public string Name
        {

            get
            {
                return (string)this["name"];
            }
            set
            {
                this["name"] = value;
            }
        }

        // Declare an element (not in a collection) of the type
        // UrlConfigElement. In the configuration
        // file it corresponds to <simple .... />.
        [ConfigurationProperty("simple")]
        public UrlConfigElement Simple
        {
            get
            {
                UrlConfigElement url =
                (UrlConfigElement)base["simple"];
                return url;
            }
        }

        // Declare a collection element represented 
        // in the configuration file by the sub-section
        // <urls> <add .../> </urls> 
        // Note: the "IsDefaultCollection = false" 
        // instructs the .NET Framework to build a nested 
        // section like <urls> ...</urls>.
        [ConfigurationProperty("urls",
            IsDefaultCollection = false)]
        public UrlsCollection Urls
        {
            get
            {
                UrlsCollection urlsCollection =
                (UrlsCollection)base["urls"];
                return urlsCollection;
            }
        }

        protected override void DeserializeSection(
            System.Xml.XmlReader reader)
        {
            base.DeserializeSection(reader);
            // You can add custom processing code here.
        }

        protected override string SerializeSection(
            ConfigurationElement parentElement,
            string name, ConfigurationSaveMode saveMode)
        {
            string s =
                base.SerializeSection(parentElement,
                name, saveMode);
            // You can add custom processing code here.
            return s;
        }
    }
}
C#
using System;
using System.Configuration;
using System.Collections;

namespace Samples.AspNet
{
    public class UrlsCollection : ConfigurationElementCollection
    {
        public UrlsCollection()
        {
            // Add one url to the collection.  This is
            // not necessary; could leave the collection 
            // empty until items are added to it outside
            // the constructor.
            UrlConfigElement url = 
                (UrlConfigElement)CreateNewElement();
            Add(url);
        }

        public override 
            ConfigurationElementCollectionType CollectionType
        {
            get
            {
                return 

                    ConfigurationElementCollectionType.AddRemoveClearMap;
            }
        }

        protected override 
            ConfigurationElement CreateNewElement()
        {
            return new UrlConfigElement();
        }

        protected override 
            ConfigurationElement CreateNewElement(
            string elementName)
        {
            return new UrlConfigElement(elementName);
        }

        protected override Object 
            GetElementKey(ConfigurationElement element)
        {
            return ((UrlConfigElement)element).Name;
        }

        public new string AddElementName
        {
            get
            { return base.AddElementName; }

            set
            { base.AddElementName = value; }
        }

        public new string ClearElementName
        {
            get
            { return base.ClearElementName; }

            set
            { base.ClearElementName = value; }
        }

        public new string RemoveElementName
        {
            get
            { return base.RemoveElementName; }
        }

        public new int Count
        {
            get { return base.Count; }
        }

        public UrlConfigElement this[int index]
        {
            get
            {
                return (UrlConfigElement)BaseGet(index);
            }
            set
            {
                if (BaseGet(index) != null)
                {
                    BaseRemoveAt(index);
                }
                BaseAdd(index, value);
            }
        }

        new public UrlConfigElement this[string Name]
        {
            get
            {
                return (UrlConfigElement)BaseGet(Name);
            }
        }

        public int IndexOf(UrlConfigElement url)
        {
            return BaseIndexOf(url);
        }

        public void Add(UrlConfigElement url)
        {
            BaseAdd(url);
            // Add custom code here.
        }

        protected override void 
            BaseAdd(ConfigurationElement element)
        {
            BaseAdd(element, false);
            // Add custom code here.
        }

        public void Remove(UrlConfigElement url)
        {
            if (BaseIndexOf(url) >= 0)
                BaseRemove(url.Name);
        }

        public void RemoveAt(int index)
        {
            BaseRemoveAt(index);
        }

        public void Remove(string name)
        {
            BaseRemove(name);
        }

        public void Clear()
        {
            BaseClear();
            // Add custom code here.
        }
    }
}
C#
using System;
using System.Configuration;
using System.Collections;

namespace Samples.AspNet
{
    public class UrlConfigElement : ConfigurationElement
    {
        // Constructor allowing name, url, and port to be specified.
        public UrlConfigElement(String newName,
            String newUrl, int newPort)
        {
            Name = newName;
            Url = newUrl;
            Port = newPort;
        }

        // Default constructor, will use default values as defined
        // below.
        public UrlConfigElement()
        {
        }

        // Constructor allowing name to be specified, will take the
        // default values for url and port.
        public UrlConfigElement(string elementName)
        {
            Name = elementName;
        }

        [ConfigurationProperty("name", 
            DefaultValue = "Microsoft",
            IsRequired = true, 
            IsKey = true)]
        public string Name
        {
            get
            {
                return (string)this["name"];
            }
            set
            {
                this["name"] = value;
            }
        }

        [ConfigurationProperty("url",
            DefaultValue = "http://www.microsoft.com",
            IsRequired = true)]
        [RegexStringValidator(@"\w+:\/\/[\w.]+\S*")]
        public string Url
        {
            get
            {
                return (string)this["url"];
            }
            set
            {
                this["url"] = value;
            }
        }

        [ConfigurationProperty("port",
            DefaultValue = (int)0,
            IsRequired = false)]
        [IntegerValidator(MinValue = 0,
            MaxValue = 8080, ExcludeRange = false)]
        public int Port
        {
            get
            {
                return (int)this["port"];
            }
            set
            {
                this["port"] = value;
            }
        }

        protected override void DeserializeElement(
           System.Xml.XmlReader reader, 
            bool serializeCollectionKey)
        {
            base.DeserializeElement(reader, 
                serializeCollectionKey);
            // You can your custom processing code here.
        }

        protected override bool SerializeElement(
            System.Xml.XmlWriter writer, 
            bool serializeCollectionKey)
        {
            bool ret = base.SerializeElement(writer, 
                serializeCollectionKey);
            // You can enter your custom processing code here.
            return ret;
        }

        protected override bool IsModified()
        {
            bool ret = base.IsModified();
            // You can enter your custom processing code here.
            return ret;
        }
    }
}

注釈

ConfigurationElementは、構成ファイル内の XML 要素 (Web.config など) を表すために使用される抽象クラスです。 構成ファイル内の要素には、0 個、1 つ以上の子要素を含めることができます。

ConfigurationElementクラスは抽象として定義されているため、そのインスタンスを作成することはできません。 クラスは、そこからしか派生できません。 .NET Framework には、 などのConfigurationSection標準 XML 構成要素をConfigurationElement表すために、 クラスから派生するクラスが含まれています。 クラスを拡張して、 ConfigurationElement カスタム構成要素とセクションにアクセスすることもできます。 このトピックで後述する例では、 から ConfigurationElement派生したカスタム クラスを使用してカスタム構成要素とセクションにアクセスする方法を示します。

、 などのConfigurationElementConfigurationElementCollectionConfigurationPropertyConfigurationSection標準構成の種類を拡張することもできます。 詳細については、これらのクラスのドキュメントを参照してください。

構成ファイルの情報にアクセスする方法の詳細については、 クラスと クラスに ConfigurationManager 関するページを WebConfigurationManager 参照してください。

注意 (実装者)

すべてのConfigurationElementオブジェクトは、要素属性または子要素のConfigurationPropertyコレクションを表す オブジェクトの内部ConfigurationPropertyCollectionコレクションを作成します。

カスタマイズ不可能な情報と機能は、 プロパティによって ElementInformation 提供される オブジェクトに ElementInformation 含まれています。

プログラムまたは宣言型 (属性付き) コーディング モデルを使用して、カスタム構成要素を作成できます。

  • プログラム モデルでは、要素属性ごとに、その値を取得または設定し、基になる ConfigurationElement 基底クラスの内部プロパティ バッグに追加するプロパティを作成する必要があります。 このモデルの使用方法の例については、 クラスを ConfigurationSection 参照してください。

  • 属性付きモデルとも呼ばれる単純な宣言モデルを使用すると、プロパティを使用して要素属性を定義し、属性で修飾できます。 これらの属性は、プロパティの種類とその既定値について ASP.NET 構成システムに指示します。 この情報をリフレクションによって取得すると、ASP.NET 構成システムによって要素プロパティ オブジェクトが自動的に作成され、必要な初期化が実行されます。 このトピックで後述する例では、このモデルの使用方法を示します。

コンストラクター

ConfigurationElement()

ConfigurationElement クラスの新しいインスタンスを初期化します。

プロパティ

CurrentConfiguration

現在の Configuration インスタンスが属している構成階層を表す最上位の ConfigurationElement インスタンスへの参照を取得します。

ElementInformation

ElementInformation オブジェクトのカスタマイズできない情報と機能を格納する ConfigurationElement オブジェクトを取得します。

ElementProperty

ConfigurationElementProperty オブジェクト自体を表す ConfigurationElement オブジェクトを取得します。

EvaluationContext

ContextInformation オブジェクトの ConfigurationElement オブジェクトを取得します。

HasContext

CurrentConfiguration プロパティが null であるかどうかを示す値を取得します。

Item[ConfigurationProperty]

この構成要素のプロパティまたは属性を取得または設定します。

Item[String]

この構成要素のプロパティ、属性、または子要素を取得または設定します。

LockAllAttributesExcept

ロックされている属性のコレクションを取得します。

LockAllElementsExcept

ロックされている要素のコレクションを取得します。

LockAttributes

ロックされている属性のコレクションを取得します。

LockElements

ロックされている要素のコレクションを取得します。

LockItem

要素がロックされているかどうかを示す値を取得または設定します。

Properties

プロパティのコレクションを取得します。

メソッド

DeserializeElement(XmlReader, Boolean)

構成ファイルから XML を読み取ります。

Equals(Object)

現在の ConfigurationElement インスタンスを、指定したオブジェクトと比較します。

GetHashCode()

現在の ConfigurationElement インスタンスを表す一意の値を取得します。

GetTransformedAssemblyString(String)

指定されたアセンブリ名を変換して返します。

GetTransformedTypeString(String)

指定された型名を変換して返します。

GetType()

現在のインスタンスの Type を取得します。

(継承元 Object)
Init()

ConfigurationElement オブジェクトを初期状態に設定します。

InitializeDefault()

ConfigurationElement オブジェクトの既定の値セットを初期化するために使用します。

IsModified()

派生クラスに実装された場合、この構成要素が最後の保存または読み込み以降に変更されたかどうかを示します。

IsReadOnly()

ConfigurationElement オブジェクトが読み取り専用かどうかを示す値を取得します。

ListErrors(IList)

この ConfigurationElement オブジェクトおよびすべてのサブ要素の無効なプロパティのエラーを、渡されたリストに追加します。

MemberwiseClone()

現在の Object の簡易コピーを作成します。

(継承元 Object)
OnDeserializeUnrecognizedAttribute(String, String)

逆シリカル化中に不明な属性が発生したかどうかを示す値を取得します。

OnDeserializeUnrecognizedElement(String, XmlReader)

逆シリカル化中に不明な要素が発生したかどうかを示す値を取得します。

OnRequiredPropertyNotFound(String)

必要なプロパティが見つからないと例外がスローされます。

PostDeserialize()

逆シリアル化後に呼び出されます。

PreSerialize(XmlWriter)

シリアル化前に呼び出されます。

Reset(ConfigurationElement)

ConfigurationElement オブジェクトの内部状態 (ロックやプロパティ コレクションなど) をリセットします。

ResetModified()

IsModified() メソッドの値が派生クラスに実装されたときに、false にリセットします。

SerializeElement(XmlWriter, Boolean)

派生クラスに実装されている場合、この構成要素の内容を構成ファイルに書き込みます。

SerializeToXmlElement(XmlWriter, String)

派生クラスに実装されている場合、この構成要素の外側のタグを構成ファイルに書き込みます。

SetPropertyValue(ConfigurationProperty, Object, Boolean)

プロパティを指定した値に設定します。

SetReadOnly()

IsReadOnly() オブジェクトおよびすべてのサブ要素に ConfigurationElement プロパティを設定します。

ToString()

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

(継承元 Object)
Unmerge(ConfigurationElement, ConfigurationElement, ConfigurationSaveMode)

保存しないすべての値を削除するには、ConfigurationElement オブジェクトを変更します。

適用対象

製品 バージョン
.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

こちらもご覧ください