您正在定义一个不属于正常配置文件的新部分:
<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);
}
}
}
还有其他读取配置文件的方法,但这是徒手键入的最简单方法。