2009-11-18 12 views
12

ho provatoC# AppSettings: C'è un modo semplice per mettere una collezione in <appSetting>

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

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

Ma ho solo l'ultimo membro. Come posso risolvere questo facilmente?

+2

soluzione più semplice è quella di utilizzare [System.Collections.Specialized.StringCollection] (http://msdn.microsoft.com/en-us/library /system.collections.specialized.stringcollection.aspx): Risposta per la domanda: [Archivia serie di stringhe in appSettings?] (http://stackoverflow.com/q/10419116/155207) – Serkan

risposta

24

Ho avuto un problema simile e l'ho fatto con questo codice. Spero che questo aiuti nel tuo problema.

In questo caso Elenco (simile alla mia URLSection) avrà una sezione di configurazione completa in web.config che è possibile ottenere tutti i valori da questa sezione quindi.

<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> 

Ho creato tre classi per questo: 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; 
    } 
} 
} 
+0

cosa molto interessante proverò questo e potrebbe chiedere aiuto se non lo capisco – Markus

+0

Ho provato questo, ma i doenst funziona ottengo questo errore: Quando si crea la sezione di configurazione gestore per "URLSection" Si è verificato un errore .: Il file o l'assembly "A, Ve rsion = 1.0.0.0, Culture = neutral, PublicKeyToken = null 'o una delle sue dipendenze non è stata trovata Ma perché? Ho appena copiato il tuo codice – Markus

+1

Markus I ha cambiato il nome di Namespace (A) in questo codice in quanto rappresentava alcune cose relative alla società in cui lavoro. Quindi potresti non essere in grado di creare il tuo codice, ma questo design lo puoi trovare in questo link: http://msdn.microsoft.com/en-us/library/2tw134k3.aspx –

1

Probabilmente sarebbe meglio mettere queste informazioni in un file XML separato e avere un riferimento a quel file in AppSettings. Ciò ti darebbe molta più flessibilità nel modo in cui hai recuperato le informazioni e l'hai consumata.

L'unica cosa sarebbe che si vorrebbe creare una classe separata (statica?) Per leggere l'XML in modo simile alla classe System.Configuration.ConfigurationManager.AppSettings.

Se, invece, DEVE essere nel file Web.Config, suggerirei che l'unico modo per ottenere ciò sarebbe semplicemente disporre di un array delimitato da [pipe/comma/semi-colon] in uno Impostazione "Elenco".

+0

: S sux, mi pare che ci deve essere simular alle collezioni in una normale app.Config tag – Markus

1

Haacked p fornisce un approccio conciso alle impostazioni di configurazione. Il suo approccio utilizza una classe derivante da ConfigurationSection. Così, per il suo esempio blog vostro app.config o web.config rappresentazione XML sarà simile a questa:

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

Questa è la pena di leggere:

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

3
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]); 
    } 
+1

+1 Bit hacky, ma mi ha risparmiato un po 'di tempo con le sezioni di configurazione personalizzate per una semplice applicazione. –

+2

Funziona solo se i tasti sono unici, ad esempio SOMESPECIAL-01, SOMESPECIAL-02, ecc. Se si ripete semplicemente SOMESPECIAL, è possibile ottenere solo l'ultimo. –

+0

@PaulGrimshaw Molto hacky e ha anche il [problema di İ turco] (http://haacked.com/archive/2012/07/05/turkish-i-problem-and-hy-you-should-care.aspx/). Faresti meglio a usare un overload con 'StringComparison' invece e [' String.StartsWith'] (https://msdn.microsoft.com/en-us/library/ms131452 (v = vs.110) .aspx) mentre tu ci siamo. – Ronald

2

NinjaSettings fa questo fuori la scatola.

Nella console di gestione dei pacchetti

Install-Package NinjaSettings 

Si potrebbe dichiarare la vostra lista come

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

quindi creare un'interfaccia con una mappatura per la lista a qualsiasi ICollection o Array

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

quindi accedi al tuo utente delle impostazioni nel wrapper NinjaSettings. In genere si sarebbe fili Questa usando IOC, ma l'uso di base è

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

    int total = 0; 
    for (var i in settings.List) 
    { 
     total+=i;   
    } 
Problemi correlati