更新 : 2007 年 11 月
名前空間 :
System.Configuration アセンブリ :
System.Configuration (System.Configuration.dll 内)
Public MustInherit Class ConfigurationSection _
Inherits ConfigurationElement
Dim instance As ConfigurationSection
public abstract class ConfigurationSection : ConfigurationElement
public ref class ConfigurationSection abstract : public ConfigurationElement
public abstract class ConfigurationSection extends ConfigurationElement
public abstract class ConfigurationSection extends ConfigurationElement
ConfigurationSection クラスを使用して、カスタムのセクション型を実装します。ConfigurationSection クラスを拡張して、カスタム ハンドリングを提供し、さらにカスタム構成セクションにプログラムからアクセスできるようにします。
セクションは、その処理型を configSections 要素のエントリに登録します。例については、「例」のセクションに示す構成ファイルの抜粋を参照してください。
メモ : |
|---|
以前のバージョンの .NET Framework では、プログラムによって構成設定を変更するために構成セクション ハンドラが使用されていました。現在、すべての既定の構成セクションは、ConfigurationSection クラスを拡張するクラスによって表されています。 |
実装元へのメモ :プログラム コーディング モデルまたは宣言 (属性付き) コーディング モデルを使用して、カスタム構成セクションを作成できます。
プログラム モデル。このモデルでは、セクション属性ごとにプロパティを作成し、その値の取得または設定を行い、その値を基になる ConfigurationElement 基本クラスの内部プロパティ バッグに追加する必要があります。
宣言モデル。属性付きモデルとも呼ばれる、このより単純なモデルを使用すると、セクション属性をプロパティを使用して定義し、属性で装飾できます。これらの属性は、ASP.NET 構成システムに対して、プロパティの型およびその既定値について指示します。リフレクションによって取得したこの情報を使用して、ASP.NET 構成システムはセクション プロパティ オブジェクトを作成し、必要な初期化を実行します。
Configuration クラスは、構成ファイルの編集をプログラムから行うことができるようにします。次に示す方法で、これらのファイルへの読み取りアクセスまたは書き込みアクセスができます。
読み取り。構成情報を読み取るには、GetSection または GetSectionGroup を使用します。読み取りを行うユーザーまたはプロセスに、次のアクセス許可が必要です。
アプリケーションが独自の構成に対する読み取り専用アクセスを行う必要がある場合は、GetSection()()() のオーバーロード メソッドを使用することをお勧めします (Web アプリケーションの場合)。または、ConfigurationManager..::.GetSection メソッドをお勧めします (クライアント アプリケーションの場合)。
これらのメソッドにより、現在のアプリケーションのキャッシュされた構成値にアクセスできます。こちらの方が、Configuration クラスよりもパフォーマンスが優れています。
メモ : |
|---|
path パラメータを受け取る静的な GetSection メソッドを使用する場合、path パラメータは、コードを実行しているアプリケーションを参照している必要があります。そうでない場合は、パラメータが無視され、現在実行中のアプリケーションの構成情報が返されます。 |
書き込み。構成情報を書き込むには、Save メソッドの 1 つを使用します。書き込みを行うユーザーまたはプロセスに、次のアクセス許可が必要です。
プログラムによってカスタム セクションを実装する方法を次のコード例に示します。
属性モデルを使用して実装されたカスタム セクションを実装および使用する方法を示す完全な例については、ConfigurationElement のトピックを参照してください。
' Define a custom section.
' The CustomSection type allows to define a custom section
' programmatically.
NotInheritable Public Class CustomSection
Inherits ConfigurationSection
' The collection (property bag) that contains
' the section properties.
Private Shared _Properties As ConfigurationPropertyCollection
' Internal flag to disable
' property setting.
Private Shared _ReadOnly As Boolean
' The FileName property.
Private Shared _FileName As New ConfigurationProperty( _
"fileName", GetType(String), _
"default.txt", _
ConfigurationPropertyOptions.IsRequired)
' The MaxUsers property.
Private Shared _MaxUsers As New ConfigurationProperty( _
"maxUsers", GetType(Long), _
CType(1000, Long), _
ConfigurationPropertyOptions.None)
' The MaxIdleTime property.
Private Shared _MaxIdleTime As New ConfigurationProperty( _
"maxIdleTime", GetType(TimeSpan), _
TimeSpan.FromMinutes(5), _
ConfigurationPropertyOptions.IsRequired)
' CustomSection constructor.
Public Sub New()
' Property initialization
_Properties = _
New ConfigurationPropertyCollection()
_Properties.Add(_FileName)
_Properties.Add(_MaxUsers)
_Properties.Add(_MaxIdleTime)
End Sub 'New
' This is a key customization.
' It returns the initialized property bag.
Protected Overrides ReadOnly Property Properties() _
As ConfigurationPropertyCollection
Get
Return _Properties
End Get
End Property
Private Shadows ReadOnly Property IsReadOnly() As Boolean
Get
Return _ReadOnly
End Get
End Property
' Use this to disable property setting.
Private Sub ThrowIfReadOnly(propertyName As String)
If IsReadOnly Then
Throw New ConfigurationErrorsException( _
"The property " + propertyName + " is read only.")
End If
End Sub 'ThrowIfReadOnly
' Customizes the use of CustomSection
' by setting _ReadOnly to false.
' Remember you must use it along with ThrowIfReadOnly.
Protected Overrides Function GetRuntimeObject() As Object
' To enable property setting just assign true to
' the following flag.
_ReadOnly = True
Return MyBase.GetRuntimeObject()
End Function 'GetRuntimeObject
<StringValidator( _
InvalidCharacters:=" ~!@#$%^&*()[]{}/;'""|\", _
MinLength:=1, MaxLength:=60)> _
Public Property FileName() As String
Get
Return CStr(Me("fileName"))
End Get
Set(ByVal value As String)
' With this you disable the setting.
' Remember that the _ReadOnly flag must
' be set to true in the GetRuntimeObject.
ThrowIfReadOnly("FileName")
Me("fileName") = value
End Set
End Property
<LongValidator( _
MinValue:=1, MaxValue:=1000000, _
ExcludeRange:=False)> _
Public Property MaxUsers() As Long
Get
Return Fix(Me("maxUsers"))
End Get
Set(ByVal value As Long)
Me("maxUsers") = Value
End Set
End Property
<TimeSpanValidator( _
MinValueString:="0:0:30", _
MaxValueString:="5:00:0", ExcludeRange:=False)> _
Public Property MaxIdleTime() As TimeSpan
Get
Return CType(Me("maxIdleTime"), TimeSpan)
End Get
Set(ByVal value As TimeSpan)
Me("maxIdleTime") = Value
End Set
End Property
End Class 'CustomSection
// Define a custom section.
// The CustomSection type allows to define a custom section
// programmatically.
public sealed class CustomSection :
ConfigurationSection
{
// The collection (property bag) that contains
// the section properties.
private static ConfigurationPropertyCollection _Properties;
// Internal flag to disable
// property setting.
private static bool _ReadOnly;
// The FileName property.
private static readonly ConfigurationProperty _FileName =
new ConfigurationProperty("fileName",
typeof(string),"default.txt",
ConfigurationPropertyOptions.IsRequired);
// The MaxUsers property.
private static readonly ConfigurationProperty _MaxUsers =
new ConfigurationProperty("maxUsers",
typeof(long), (long)1000,
ConfigurationPropertyOptions.None);
// The MaxIdleTime property.
private static readonly ConfigurationProperty _MaxIdleTime =
new ConfigurationProperty("maxIdleTime",
typeof(TimeSpan), TimeSpan.FromMinutes(5),
ConfigurationPropertyOptions.IsRequired);
// CustomSection constructor.
public CustomSection()
{
// Property initialization
_Properties =
new ConfigurationPropertyCollection();
_Properties.Add(_FileName);
_Properties.Add(_MaxUsers);
_Properties.Add(_MaxIdleTime);
}
// This is a key customization.
// It returns the initialized property bag.
protected override ConfigurationPropertyCollection Properties
{
get
{
return _Properties;
}
}
private new bool IsReadOnly
{
get
{
return _ReadOnly;
}
}
// Use this to disable property setting.
private void ThrowIfReadOnly(string propertyName)
{
if (IsReadOnly)
throw new ConfigurationErrorsException(
"The property " + propertyName + " is read only.");
}
// Customizes the use of CustomSection
// by setting _ReadOnly to false.
// Remember you must use it along with ThrowIfReadOnly.
protected override object GetRuntimeObject()
{
// To enable property setting just assign true to
// the following flag.
_ReadOnly = true;
return base.GetRuntimeObject();
}
[StringValidator(InvalidCharacters = " ~!@#$%^&*()[]{}/;'\"|\\",
MinLength = 1, MaxLength = 60)]
public string FileName
{
get
{
return (string)this["fileName"];
}
set
{
// With this you disable the setting.
// Remember that the _ReadOnly flag must
// be set to true in the GetRuntimeObject.
ThrowIfReadOnly("FileName");
this["fileName"] = value;
}
}
[LongValidator(MinValue = 1, MaxValue = 1000000,
ExcludeRange = false)]
public long MaxUsers
{
get
{
return (long)this["maxUsers"];
}
set
{
this["maxUsers"] = value;
}
}
[TimeSpanValidator(MinValueString = "0:0:30",
MaxValueString = "5:00:0",
ExcludeRange = false)]
public TimeSpan MaxIdleTime
{
get
{
return (TimeSpan)this["maxIdleTime"];
}
set
{
this["maxIdleTime"] = value;
}
}
}
前述のコード例に適用している構成ファイルの抜粋を次に示します。
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="CustomSection" type="Samples.AspNet. CustomSection, CustomConfigurationSection, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" allowDefinition="Everywhere" allowExeDefinition="MachineToApplication" restartOnExternalChanges="true" />
</configSections>
<CustomSection fileName="default.txt" maxUsers="1000" maxIdleTime="00:15:00" />
</configuration>
System..::.Object
System.Configuration..::.ConfigurationElement
System.Configuration..::.ConfigurationSection
System.Configuration..::.AppSettingsSection
System.Configuration..::.ClientSettingsSection
System.Configuration..::.ConnectionStringsSection
System.Configuration..::.DefaultSection
System.Configuration..::.IgnoreSection
System.Configuration..::.ProtectedConfigurationSection
System.Net.Configuration..::.AuthenticationModulesSection
System.Net.Configuration..::.ConnectionManagementSection
System.Net.Configuration..::.DefaultProxySection
System.Net.Configuration..::.RequestCachingSection
System.Net.Configuration..::.SettingsSection
System.Net.Configuration..::.SmtpSection
System.Net.Configuration..::.WebRequestModulesSection
System.Runtime.Serialization.Configuration..::.DataContractSerializerSection
System.ServiceModel.Activation.Configuration..::.DiagnosticSection
System.ServiceModel.Activation.Configuration..::.NetPipeSection
System.ServiceModel.Activation.Configuration..::.NetTcpSection
System.ServiceModel.Configuration..::.BehaviorsSection
System.ServiceModel.Configuration..::.BindingsSection
System.ServiceModel.Configuration..::.ClientSection
System.ServiceModel.Configuration..::.ComContractsSection
System.ServiceModel.Configuration..::.CommonBehaviorsSection
System.ServiceModel.Configuration..::.DiagnosticSection
System.ServiceModel.Configuration..::.ExtensionsSection
System.ServiceModel.Configuration..::.ServiceHostingEnvironmentSection
System.ServiceModel.Configuration..::.ServicesSection
System.Transactions.Configuration..::.DefaultSettingsSection
System.Transactions.Configuration..::.MachineSettingsSection
System.Web.Configuration..::.AnonymousIdentificationSection
System.Web.Configuration..::.AuthenticationSection
System.Web.Configuration..::.AuthorizationSection
System.Web.Configuration..::.CacheSection
System.Web.Configuration..::.ClientTargetSection
System.Web.Configuration..::.CompilationSection
System.Web.Configuration..::.CustomErrorsSection
System.Web.Configuration..::.DeploymentSection
System.Web.Configuration..::.GlobalizationSection
System.Web.Configuration..::.HealthMonitoringSection
System.Web.Configuration..::.HostingEnvironmentSection
System.Web.Configuration..::.HttpCookiesSection
System.Web.Configuration..::.HttpHandlersSection
System.Web.Configuration..::.HttpModulesSection
System.Web.Configuration..::.HttpRuntimeSection
System.Web.Configuration..::.IdentitySection
System.Web.Configuration..::.MachineKeySection
System.Web.Configuration..::.MembershipSection
System.Web.Configuration..::.OutputCacheSection
System.Web.Configuration..::.OutputCacheSettingsSection
System.Web.Configuration..::.PagesSection
System.Web.Configuration..::.ProcessModelSection
System.Web.Configuration..::.ProfileSection
System.Web.Configuration..::.RoleManagerSection
System.Web.Configuration..::.ScriptingAuthenticationServiceSection
System.Web.Configuration..::.ScriptingJsonSerializationSection
System.Web.Configuration..::.ScriptingProfileServiceSection
System.Web.Configuration..::.ScriptingRoleServiceSection
System.Web.Configuration..::.ScriptingScriptResourceHandlerSection
System.Web.Configuration..::.SecurityPolicySection
System.Web.Configuration..::.SessionPageStateSection
System.Web.Configuration..::.SessionStateSection
System.Web.Configuration..::.SiteMapSection
System.Web.Configuration..::.SqlCacheDependencySection
System.Web.Configuration..::.TraceSection
System.Web.Configuration..::.TrustSection
System.Web.Configuration..::.UrlMappingsSection
System.Web.Configuration..::.WebControlsSection
System.Web.Configuration..::.WebPartsSection
System.Web.Configuration..::.XhtmlConformanceSection
System.Web.Mobile..::.DeviceFiltersSection
System.Web.Services.Configuration..::.WebServicesSection
System.Web.UI.MobileControls..::.MobileControlsSection
System.Windows.Forms..::.WindowsFormsSection
System.Workflow.Activities.Configuration..::.ActiveDirectoryRoleFactoryConfiguration
System.Workflow.Activities..::.ExternalDataExchangeServiceSection
System.Workflow.Runtime.Configuration..::.WorkflowRuntimeSection
System.Xml.Serialization.Configuration..::.DateTimeSerializationSection
System.Xml.Serialization.Configuration..::.SchemaImporterExtensionsSection
System.Xml.Serialization.Configuration..::.XmlSerializerSection
この型のすべてのパブリック 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
参照
その他の技術情報