Retrieving values from a configuration file that uses the section defined by System.Configuration.NameValueSectionHandler is easy when you use the current configuration file for the application.
Example configuration file.
<configuration> <configSections> <section name="MyParams" type="System.Configuration.NameValueSectionHandler" /> </configSections> <MyParams> <add key="FirstParam" value="One"/> <add key="SecondParam" value="Two"/> </MyParams> </configuration>
Sample code that reads it easily.
NameValueCollection myParamsCollection = ConfigurationManager.GetSection("MyParams") as NameValueCollection;
This is code that does not work.
NameValueCollection collection = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None) .GetSection("MyParams") as NameValueCollection;
The following compilation error failed.
It is not possible to convert the type "System.Configuration.ConfigurationSection" to "System.Collections.Specialized.NameValueCollection" through a reference conversion, box conversion, conversion for decompression, conversion conversion or null type conversion.
ConfigurationManager.OpenExeConfiguration (ConfigurationUserLevel.None) returns System.Configuration.Configuration, and Configuration.GetSection returns ConfigurationSection.
ConfigurationManager.GetSection returns an object.
So, how do I get my NameValueCollection back when I need to use OpenExeConfiguration?
source share