Пользовательское приложение.раздел конфигурации с простым списком" добавить " элементы
как создать пользовательское приложение.раздел конфигурации, который является просто простым списком add элементов?
я нашел несколько примеров (например,как создать пользовательский раздел конфигурации в приложении.конфиг?) для пользовательских разделов, которые выглядят так:
<RegisterCompanies>
<Companies>
<Company name="Tata Motors" code="Tata"/>
<Company name="Honda Motors" code="Honda"/>
</Companies>
</RegisterCompanies>
но как мне избежать дополнительного элемента коллекции ("компании"), чтобы он выглядел так же, как appSettings и connectionStrings разделы? Другими словами, Я хотел бы:
<registerCompanies>
<add name="Tata Motors" code="Tata"/>
<add name="Honda Motors" code="Honda"/>
</registerCompanies>
5 ответов:
полный пример с кодом на основе файла конфигурации 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>вот пример кода для реализации пользовательского раздела конфигурации с свернутой коллекцией
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; } } } }вот пример, как получить доступ к информации о конфигурации от кода.
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); }
нет необходимости в разделе пользовательской конфигурации.
приложение.Конфигурации
<?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>извлечь
// This casts to a NameValueCollection because the section is defined as a /// AppSettingsSection in the configSections. NameValueCollection settingCollection = (NameValueCollection)ConfigurationManager.GetSection("YourAppSettings"); var items = settingCollection.Count; Debug.Assert(items == 4); // no duplicates... the last one wins. Debug.Assert(settingCollection["duplicate"] == "bb"); // Just keys as per original question? done... use em. string[] allKeys = settingCollection.AllKeys; // maybe you did want key/value pairs. This is flexible to accommodate both. foreach (string key in allKeys) { Console.WriteLine(key + " : " + settingCollection[key]); }
на основе Джей Уокер!--5--> ответ выше, это полный рабочий пример, который добавляет возможность делать индексирование:
<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>вот пример кода для реализации пользовательского раздела конфигурации с свернутой коллекцией
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; } } } }вот пример, как получить доступ к информации о конфигурации от кода.
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); }
основываясь на ответе Джея Уокера, доступ к элементам должен быть выполнен путем итерации по коллекции "экземпляры". то есть.
var config = ConfigurationManager.GetSection("registerCompanies") as MyConfigSection; foreach (MyConfigInstanceElement e in config.Instances) { Console.WriteLine("Name: {0}, Code: {1}", e.Name, e.Code); }
мой.Сборка в конфигурации дала мне исключение, потому что я назвал проект "Мой" не "мой".Собрание." Будьте осторожны, если вы используете этот пример!
Comments