[英]Custom app.config section with a simple list of “add” elements
How do I create a custom app.config section that is just a simple list of add
elements?如何创建一个自定义 app.config 部分,它只是一个简单的
add
元素列表?
I have found a few examples (eg How to create custom config section in app.config? ) for custom sections that look like this:我找到了一些示例(例如,如何在 app.config 中创建自定义配置部分? )用于如下所示的自定义部分:
<RegisterCompanies>
<Companies>
<Company name="Tata Motors" code="Tata"/>
<Company name="Honda Motors" code="Honda"/>
</Companies>
</RegisterCompanies>
But how do I avoid the extra collection element ("Companies") so that it looks the same as the appSettings
and connectionStrings
sections?但是如何避免额外的集合元素(“公司”),使其看起来与
appSettings
和connectionStrings
部分相同? In other words, I'd like:换句话说,我想:
<registerCompanies>
<add name="Tata Motors" code="Tata"/>
<add name="Honda Motors" code="Honda"/>
</registerCompanies>
Full example with code based on OP config file:基于 OP 配置文件的代码完整示例:
<configuration>
<configSections>
<section name="registerCompanies"
type="My.MyConfigSection, My.Assembly" />
</configSections>
<registerCompanies>
<add name="Tata Motors" code="Tata"/>
<add name="Honda Motors" code="Honda"/>
</registerCompanies>
</configuration>
Here is the sample code to implement a custom config section with collapsed collection这是实现带有折叠集合的自定义配置部分的示例代码
using System.Configuration;
namespace My {
public class MyConfigSection : ConfigurationSection {
[ConfigurationProperty("", IsRequired = true, IsDefaultCollection = true)]
public MyConfigInstanceCollection Instances {
get { return (MyConfigInstanceCollection)this[""]; }
set { this[""] = value; }
}
}
public class MyConfigInstanceCollection : ConfigurationElementCollection {
protected override ConfigurationElement CreateNewElement() {
return new MyConfigInstanceElement();
}
protected override object GetElementKey(ConfigurationElement element) {
//set to whatever Element Property you want to use for a key
return ((MyConfigInstanceElement)element).Name;
}
}
public class MyConfigInstanceElement : ConfigurationElement {
//Make sure to set IsKey=true for property exposed as the GetElementKey above
[ConfigurationProperty("name", IsKey = true, IsRequired = true)]
public string Name {
get { return (string) base["name"]; }
set { base["name"] = value; }
}
[ConfigurationProperty("code", IsRequired = true)]
public string Code {
get { return (string) base["code"]; }
set { base["code"] = value; }
} } }
Here is an example of how to access the configuration information from code.以下是如何从代码访问配置信息的示例。
var config = ConfigurationManager.GetSection("registerCompanies")
as MyConfigSection;
Console.WriteLine(config["Tata Motors"].Code);
foreach (var e in config.Instances) {
Console.WriteLine("Name: {0}, Code: {1}", e.Name, e.Code);
}
No custom configuration section necessary.不需要自定义配置部分。
app.config应用程序配置文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="YourAppSettings" type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</configSections>
<!-- value attribute is optional. omit if you just want a list of 'keys' -->
<YourAppSettings>
<add key="one" value="1" />
<add key="two" value="2"/>
<add key="three" value="3"/>
<add key="duplicate" value="aa"/>
<add key="duplicate" value="bb"/>
</YourAppSettings>
</configuration>
Retrieve values检索值
// AppSettingsSection can be cast to a NameValueCollection
NameValueCollection settingCollection =
(NameValueCollection)ConfigurationManager.GetSection("YourAppSettings");
// An array of the keys. No Duplicates
// { "one", "two", "three", "duplicate" }
string[] allKeys = settingCollection.AllKeys;
// key/value pairs
// one : 1
// two : 2
// three : 3
// duplicate : bb
foreach (string key in allKeys)
{
Console.WriteLine(key + " : " + settingCollection[key]);
}
// Duplicates behavior
var items = settingCollection.Count;
Debug.Assert(items == 4); // no duplicates. Last element wins.
Debug.Assert(settingCollection["duplicate"] == "bb");
Based on Jay Walker's answer above, this is a complete working example that adds the ability to do the indexing:基于上面Jay Walker 的回答,这是一个完整的工作示例,增加了进行索引的能力:
<configuration>
<configSections>
<section name="registerCompanies"
type="My.MyConfigSection, My.Assembly" />
</configSections>
<registerCompanies>
<add name="Tata Motors" code="Tata"/>
<add name="Honda Motors" code="Honda"/>
</registerCompanies>
</configuration>
Here is the sample code to implement a custom config section with collapsed collection这是实现带有折叠集合的自定义配置部分的示例代码
using System.Configuration;
using System.Linq;
namespace My
{
public class MyConfigSection : ConfigurationSection
{
[ConfigurationProperty("", IsRequired = true, IsDefaultCollection = true)]
public MyConfigInstanceCollection Instances
{
get { return (MyConfigInstanceCollection)this[""]; }
set { this[""] = value; }
}
}
public class MyConfigInstanceCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new MyConfigInstanceElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
//set to whatever Element Property you want to use for a key
return ((MyConfigInstanceElement)element).Name;
}
public new MyConfigInstanceElement this[string elementName]
{
get
{
return this.OfType<MyConfigInstanceElement>().FirstOrDefault(item => item.Name == elementName);
}
}
}
public class MyConfigInstanceElement : ConfigurationElement
{
//Make sure to set IsKey=true for property exposed as the GetElementKey above
[ConfigurationProperty("name", IsKey = true, IsRequired = true)]
public string Name
{
get { return (string)base["name"]; }
set { base["name"] = value; }
}
[ConfigurationProperty("code", IsRequired = true)]
public string Code
{
get { return (string)base["code"]; }
set { base["code"] = value; }
}
}
}
Here is an example of how to access the configuration information from code.以下是如何从代码访问配置信息的示例。
MyConfigSection config =
ConfigurationManager.GetSection("registerCompanies") as MyConfigSection;
Console.WriteLine(config.Instances["Honda Motors"].Code);
foreach (MyConfigInstanceElement e in config.Instances)
{
Console.WriteLine("Name: {0}, Code: {1}", e.Name, e.Code);
}
Based on the answer by Jay Walker, accessing the elements needs to be done by iterating through the "Instances" collection.根据 Jay Walker 的回答,需要通过迭代“Instances”集合来访问元素。 ie.
IE。
var config = ConfigurationManager.GetSection("registerCompanies")
as MyConfigSection;
foreach (MyConfigInstanceElement e in config.Instances) {
Console.WriteLine("Name: {0}, Code: {1}", e.Name, e.Code);
}
My.Assembly in config gave me Exception, because I named project "My" not "My.Assembly". 配置中的My.Assembly给了我异常,因为我将项目“ My”命名为“ My.Assembly”。 Be careful, if you use this example!
如果使用此示例,请当心!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.