通常の構成ファイルの一部ではない新しいセクションを定義しています。
<mySettings>
<add name="myname" myvalue="value1"/>
</mySettings>
独自のセクションを組み込むには、特定のセクションを読むために何かを書く必要があります。次に、セクションを処理するハンドラーへの参照を次のように追加します。
<configuration>
<configSections>
<section name="mySettings" type="MyAssembly.MySettingsConfigurationHander, MyAssembly"/>
</configSections>
<!-- Same as before -->
</configuration>
サンプル コード サンプルは次のようになります。
public class MySettingsSection
{
public IEnumerable<MySetting> MySettings { get;set; }
}
public class MySetting
{
public string Name { get;set; }
public string MyValue { get;set; }
}
public class MySettingsConfigurationHander : IConfigurationSectionHandler
{
public object Create(XmlNode startNode)
{
var mySettingsSection = new MySettingsSection();
mySettingsSection.MySettings = (from node in startNode.Descendents()
select new MySetting
{
Name = node.Attribute("name"),
MyValue = node.Attribute("myValue")
}).ToList();
return mySettingsSection;
}
}
public class Program
{
public static void Main()
{
var section = ConfigurationManager.GetSection("mySettings") as MySettingsSection;
Console.WriteLine("Here are the settings for 'MySettings' :");
foreach(var setting in section.MySettings)
{
Console.WriteLine("Name: {0}, MyValue: {1}", setting.Name, setting.MyValue);
}
}
}
構成ファイルを読み取る方法は他にもありますが、これはフリーハンドで入力する最も簡単な方法です。