69 votes

Comment obtenir les valeurs d'une ConfigurationSection de type NameValueSectionHandler

Je travaille avec C#, Framework 3.5 (VS 2008).

Je suis à l'aide de l' ConfigurationManager de charger un fichier de configuration (pas l'application par défaut.fichier de configuration) dans un objet de Configuration.

À l'aide de la Configuration de la classe, j'ai été en mesure d'obtenir un ConfigurationSection, mais je ne pouvais pas trouver un moyen d'obtenir les valeurs de cette section.

Dans la config, l' ConfigurationSection est de type System.Configuration.NameValueSectionHandler.

Pour ce que ça vaut, lorsque j'ai utilisé la méthode de GetSection de la ConfigurationManager (ne fonctionne que lorsqu'il était sur mon application par défaut.fichier de config), j'ai reçu un type d'objet, que je pouvais jeté dans la collection de paires clé-valeur, et je viens de recevoir la valeur comme un Dictionnaire. Je ne pouvais pas faire une telle fonte quand j'ai reçu ConfigurationSection classe à partir de la classe de Configuration toutefois.

EDIT: Exemple du fichier de configuration:

<configuration>
  <configSections>
    <section name="MyParams" 
             type="System.Configuration.NameValueSectionHandler" />
  </configSections>

  <MyParams>
    <add key="FirstParam" value="One"/>
    <add key="SecondParam" value="Two"/>
  </MyParams>
</configuration>

Exemple de la façon dont j'ai été capable de l'utiliser quand il était sur app.config (la "GetSection" la méthode est pour le défaut d'application.config uniquement):

NameValueCollection myParamsCollection =
             (NameValueCollection)ConfigurationManager.GetSection("MyParams");

Console.WriteLine(myParamsCollection["FirstParam"]);
Console.WriteLine(myParamsCollection["SecondParam"]);

28voto

nerijus Points 136

Souffert de problème exact. Le problème était dû à NameValueSectionHandler dans le fichier .config. Vous devez utiliser AppSettingsSection à la place:

 <configuration>

 <configSections>
    <section  name="DEV" type="System.Configuration.AppSettingsSection" />
    <section  name="TEST" type="System.Configuration.AppSettingsSection" />
 </configSections>

 <TEST>
    <add key="key" value="value1" />
 </TEST>

 <DEV>
    <add key="key" value="value2" />
 </DEV>

</configuration>
 

puis en code C #:

 AppSettingsSection section = (AppSettingsSection)ConfigurationManager.GetSection("TEST");
 

btw NameValueSectionHandler n'est plus pris en charge en 2.0.

19voto

MonkeyWrench Points 813

Voici un bon post qui montre comment le faire.

Si vous voulez lire les valeurs à partir d'un autre fichier que l'application.config, il faut le charger dans le ConfigurationManager.

Essayez cette méthode: ConfigurationManager.OpenMappedExeConfiguration()

Il y a un exemple de la façon de l'utiliser dans l'article MSDN.

15voto

Steven Ball Points 187

Essayez d’utiliser un AppSettingsSection au lieu d’un NameValueCollection . Quelque chose comme ça:

 var section = (AppSettingsSection)config.GetSection(sectionName);
string results = section.Settings[key].Value;
 

Source: http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/d5079420-40cb-4255-9b3b-f9a41a1f7ad2/

8voto

Steven Padfield Points 307

La seule façon pour que cela fonctionne est d'instancier manuellement le type de gestionnaire de section, de lui transmettre le code XML brut et de convertir l'objet résultant.

Cela semble plutôt inefficace, mais voilà.

J'ai écrit une méthode d'extension pour encapsuler ceci:

 public static class ConfigurationSectionExtensions
{
    public static T GetAs<T>(this ConfigurationSection section)
    {
        var sectionInformation = section.SectionInformation;

        var sectionHandlerType = Type.GetType(sectionInformation.Type);
        if (sectionHandlerType == null)
        {
            throw new InvalidOperationException(string.Format("Unable to find section handler type '{0}'.", sectionInformation.Type));
        }

        IConfigurationSectionHandler sectionHandler;
        try
        {
            sectionHandler = (IConfigurationSectionHandler)Activator.CreateInstance(sectionHandlerType);
        }
        catch (InvalidCastException ex)
        {
            throw new InvalidOperationException(string.Format("Section handler type '{0}' does not implement IConfigurationSectionHandler.", sectionInformation.Type), ex);
        }

        var rawXml = sectionInformation.GetRawXml();
        if (rawXml == null)
        {
            return default(T);
        }

        var xmlDocument = new XmlDocument();
        xmlDocument.LoadXml(rawXml);

        return (T)sectionHandler.Create(null, null, xmlDocument.DocumentElement);
    }
}
 

La manière dont vous l'appeleriez dans votre exemple est la suivante:

 var map = new ExeConfigurationFileMap
{
    ExeConfigFilename = @"c:\\foo.config"
};
var configuration = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
var myParamsSection = configuration.GetSection("MyParams");
var myParamsCollection = myParamsSection.GetAs<NameValueCollection>();
 

4voto

Peter Ivan Points 609

C'est une vieille question, mais j'utilise la classe suivante pour faire le travail. Il est basé sur le blog de Scott Dorman :

 public class NameValueCollectionConfigurationSection : ConfigurationSection
{
    private const string COLLECTION_PROP_NAME = "";

    public IEnumerable<KeyValuePair<string, string>> GetNameValueItems()
    {
        foreach ( string key in this.ConfigurationCollection.AllKeys )
        {
            NameValueConfigurationElement confElement = this.ConfigurationCollection[key];
            yield return new KeyValuePair<string, string>
                (confElement.Name, confElement.Value);
        }
    }

    [ConfigurationProperty(COLLECTION_PROP_NAME, IsDefaultCollection = true)]
    protected NameValueConfigurationCollection ConfCollection
    {
        get
        {
            return (NameValueConfigurationCollection) base[COLLECTION_PROP_NAME];
        }
    }
 

L'utilisation est simple:

 Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
NameValueCollectionConfigurationSection config = 
    (NameValueCollectionConfigurationSection) configuration.GetSection("MyParams");

NameValueCollection myParamsCollection = new NameValueCollection();
config.GetNameValueItems().ToList().ForEach(kvp => myParamsCollection.Add(kvp));
 

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X