GetSection object cannot be cast to IDictionary<>

2.3k views Asked by At

I hope I'm just missing something simple. I need to read/write to a section of my exe.config file. I have this in my code:

var appConfiguration = ConfigurationManager.OpenExeConfiguration("Mytest.Console.exe");
var fileEnvironment = appConfiguration.GetSection("fileEnvironment");

and this is my app.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="fileEnvironment" type="System.Configuration.DictionarySectionHandler"/>
    </configSections>

    <fileEnvironment>
        <add key="TestEntry1" value="A nice value"/>
        <add key="TestEntry2" value="Another value"/>
    </fileEnvironment>
</configuration>

My appConfiguration variable is returned as {System.Configuration.Configuration} and the "HasFile" property is set to true.

Without casting my variable "fileEnvironment" is returned as System.Configuration.DefaultSection. When I add as IDictionary<string, string> to the GetSection method fileEnvironment is null.

Any ideas?

2

There are 2 answers

0
JimBoone On BEST ANSWER

I kept researching the dictionary issue and came up with this stackoverflow Q&A! It produces a collection instead of a dictionary, but points the way to a solution. Thanks for everyone's time.

0
Kurt Hutchinson On

According to this old article, when a section is implemented using DictionarySectionHandler, ConfigurationManager.GetSection() will return a non-generic IDictionary, and not an IDictionary<T,V>. That's why your cast failed.

Although in modern times, it looks like it actually returns a HashTable.