How to get the values of a ConfigurationSection of type NameValueSectionHandler

C#ConfigConfigurationmanagerConfigurationsection

C# Problem Overview


I'm working with C#, Framework 3.5 (VS 2008).

I'm using the ConfigurationManager to load a config (not the default app.config file) into a Configuration object.

Using the Configuration class, I was able to get a ConfigurationSection, but I could not find a way to get the values of that section.

In the config, the ConfigurationSection is of type System.Configuration.NameValueSectionHandler.

For what it worth, when I used the method GetSection of the ConfigurationManager (works only when it was on my default app.config file), I received an object type, that I could cast into collection of pairs of key-value, and I just received the value like a Dictionary. I could not do such cast when I received ConfigurationSection class from the Configuration class however.

EDIT: Example of the config file:

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

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

Example of the way i was able to use it when it was on app.config (the "GetSection" method is for the default app.config only):

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

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

C# Solutions


Solution 1 - C#

Suffered from exact issue. Problem was because of NameValueSectionHandler in .config file. You should use AppSettingsSection instead:

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

then in C# code:

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

btw NameValueSectionHandler is not supported any more in 2.0.

Solution 2 - C#

Here's a good post that shows how to do it.

If you want to read the values from a file other than the app.config, you need to load it into the ConfigurationManager.

Try this method: ConfigurationManager.OpenMappedExeConfiguration()

There's an example of how to use it in the MSDN article.

Solution 3 - C#

Try using an AppSettingsSection instead of a NameValueCollection. Something like this:

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/

Solution 4 - C#

The only way I can get this to work is to manually instantiate the section handler type, pass the raw XML to it, and cast the resulting object.

Seems pretty inefficient, but there you go.

I wrote an extension method to encapsulate this:

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);
    }
}

The way you would call it in your example is:

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>();

Solution 5 - C#

This is an old question, but I use the following class to do the job. It's based on Scott Dorman's blog:

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];
		}
	}

The usage is straightforward:

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

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

Solution 6 - C#

Here are some examples from this blog mentioned earlier:

<configuration>    
   <Database>    
      <add key="ConnectionString" value="data source=.;initial catalog=NorthWind;integrated security=SSPI"/>    
   </Database>    
</configuration>  

get values:

 NameValueCollection db = (NameValueCollection)ConfigurationSettings.GetConfig("Database");         
    labelConnection2.Text = db["ConnectionString"];

-

Another example:

<Locations 
   ImportDirectory="C:\Import\Inbox"
   ProcessedDirectory ="C:\Import\Processed"
   RejectedDirectory ="C:\Import\Rejected"
/>

get value:

Hashtable loc = (Hashtable)ConfigurationSettings.GetConfig("Locations"); 
 
labelImport2.Text = loc["ImportDirectory"].ToString();
labelProcessed2.Text = loc["ProcessedDirectory"].ToString();

Solution 7 - C#

Try this;

Credit: https://www.limilabs.com/blog/read-system-net-mailsettings-smtp-settings-web-config

SmtpSection section = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");

string from = section.From;
string host = section.Network.Host;
int port = section.Network.Port;
bool enableSsl = section.Network.EnableSsl;
string user = section.Network.UserName;
string password = section.Network.Password;

Solution 8 - C#

This works like a charm

dynamic configSection = ConfigurationManager.GetSection("MyParams");
var theValue = configSection["FirstParam"];

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLiran BView Question on Stackoverflow
Solution 1 - C#nerijusView Answer on Stackoverflow
Solution 2 - C#MonkeyWrenchView Answer on Stackoverflow
Solution 3 - C#Steven BallView Answer on Stackoverflow
Solution 4 - C#Steven PadfieldView Answer on Stackoverflow
Solution 5 - C#Peter IvanView Answer on Stackoverflow
Solution 6 - C#RayLovelessView Answer on Stackoverflow
Solution 7 - C#Sedat KumcuView Answer on Stackoverflow
Solution 8 - C#aj goView Answer on Stackoverflow