C# AppSettings: Is there a easy way to put a collection into <appSetting>
Asked Answered
E

5

15

i tried

<appSettings >
    <add key="List" value="1"/>
    <add key="List" value="2"/>
    <add key="List" value="3"/>
  </appSettings >

and System.Configuration.ConfigurationManager.AppSettings.GetValues("List");

But i only get the last member . How could i solve this easily?

Enlargement answered 18/11, 2009 at 11:36 Comment(2)
simplest solution is to use System.Collections.Specialized.StringCollection: Answered for question: Store String Array In appSettings?Royston
https://mcmap.net/q/235342/-custom-app-config-section-with-a-simple-list-of-quot-add-quot-elements gives a super simple solution that requires no new classes, and avoids any hacky split-by-separator.Cazzie
R
26

I have dealt a similar issue and I did it with this code. Hope this helps in your problem.

In this case List (similar to my URLSection) will have a full configuration Section in web.config which you can get all values from this section then.

<configSections>
    <section name="URLSection" type="A.WebConfigSection,A,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null"/>
</configSections>

<appSettings></appSettings>

<URLSection>
    <urlCollection>
        <add url="1" value="a"/>
        <add url="2" value="b"/>
    </urlCollection>
</URLSection>

I made three classes for this: ConfigElement, ConfigElementCollection, WebConfigSection.

ConfigElement

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;

namespace A
{
  public class ConfigElement:System.Configuration.ConfigurationElement
{
    [ConfigurationProperty("url",IsRequired=true) ]
    public string url
    {
        get
        {
            return this["url"] as string;
        }
    }

    [ConfigurationProperty("value", IsRequired = true)]
    public string value
    {
        get
        {
            return this["value"] as string;
        }
    }



  }
}

ConfigElementCollection

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;

namespace A
{
  public class ConfigElementCollection:ConfigurationElementCollection
 {
    public ConfigElement this[int index]
    {
        get
        {
            return base.BaseGet(index) as ConfigElement;
        }

    }

    protected override ConfigurationElement CreateNewElement()
    {
        return new ConfigElement();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((ConfigElement)(element)).url;
    }
 }
}

WebConfigSection

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;

namespace A
{
 public class WebConfigSection:ConfigurationSection
 {

    public WebConfigSection()
    {

    }

    [ConfigurationProperty("urlCollection")]
    public ConfigElementCollection allValues
    {
        get
        {
            return this["urlCollection"] as ConfigElementCollection;
        }
    }

    public static WebConfigSection GetConfigSection()
    {
        return ConfigurationSettings.GetConfig("URLSection") as WebConfigSection;
    }
 }
}
Regale answered 18/11, 2009 at 11:56 Comment(5)
very intersting thing i will try this and may ask for help if i dont get itEnlargement
I tried this but i doenst works i get this error: When creating the configuration section handler for "URLSection" An error has occurred.: The file or assembly "A, Version = 1.0.0.0, Culture = neutral, PublicKeyToken = null 'or one of its dependencies was not found But why? i just copied your codeEnlargement
Markus I changed the Namespace (A) name in this code as it represented some stuff related to company I work in. Thus might be you are not able to build your code, but this design you can find in this link: msdn.microsoft.com/en-us/library/2tw134k3.aspxRegale
Could you add sample code how to retrieve the urlCollection from config file?Desdee
@Desdee var configUrls = WebConfigSection.GetConfigSection();Visual
B
4
    foreach (string str in ConfigurationManager.AppSettings.AllKeys)
    {
        if (str.ToUpper().IndexOf("SOMESPECIAL") > -1) //the somespecial ones you want to add in
            lstList.Add(ConfigurationManager.AppSettings[str]);
    }
Bandwidth answered 13/1, 2012 at 17:39 Comment(3)
+1 Bit hacky, but saved me some time messing with custom config sections for a simple application.Flinn
This only works if the keys are unique, i.e. SOMESPECIAL-01, SOMESPECIAL-02, etc. If you simply repeat SOMESPECIAL you can only get the last one.Dyanna
@PaulGrimshaw Very hacky indeed and also has the Turkish İ problem. You'd better use an overload with StringComparison instead and String.StartsWith while you're at it.Remanence
S
3

NinjaSettings does this out of the box.

In the package manager console

Install-Package NinjaSettings

You would declare your list as

  <appSettings>
    <add key="List" value="50,20,10,100"/>
  </appSettings>

then create an Interface with a mapping for list to any ICollection or Array

public interface IAppSettings
{
    List<int> List { get; }
}

then access your settings user the NinjaSettings wrapper. Generally you would wire this up using IOC, but the basic usage is

   var settings = new NinjaSettings<IAppSettings>().Settings;

   int total = 0;
   for (var i in settings.List) 
   {
      total+=i;        
   }
Sleekit answered 31/12, 2013 at 6:24 Comment(0)
F
1

You'd likely be better off putting this information in a separate XML file and having a reference to that file in AppSettings. That would give you a lot more flexibility around how you retrieved the information and consumed it.

The only thing would be that you'd want to create a separate (static?) class for reading the XML in a similar fashion to the System.Configuration.ConfigurationManager.AppSettings class.

If, on the other hand, it HAD to be in your Web.Config file, I would suggest the only way to achieve this simply would be to have a [pipe/comma/semi-colon] delimited array in one "List" setting.

Firenze answered 18/11, 2009 at 11:42 Comment(1)
:S sux, i thougth there must be simular to the collections in a normal app.Config <aplicationConfiguration> tagEnlargement
N
1

Haacked provides a concise approach to configuration settings. His approach uses one class deriving from ConfigurationSection. So for his blog example your app.config or web.config xml representation will look like this:

<configuration>
  <configSections>
    <section name="BlogSettings" type="Fully.Qualified.TypeName.BlogSettings,   
      AssemblyName" />
  </configSections>
  <BlogSettings frontPagePostCount="10" title="You’ve Been Haacked" />
</configuration>

This is worth a read:

http://haacked.com/archive/2007/03/12/custom-configuration-sections-in-3-easy-steps.aspx

Normandnormandy answered 30/9, 2011 at 13:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.