Natsuki_Kato
Natsuki_Kato

Reputation: 157

System.InvalidCastException after adding customize section in app.config

I want to create a simple section without writing any class by myself, I have read other posts and tried building my own section but it throws an exception of System.InvalidCastException when I try to get my section. Could anyone tell me how I can solve it? thanks!

Exception message:

An unhandled exception of type 'System.InvalidCastException' occurred in HttpServer.exe

Additional information: Unable to cast object of type 'System.Configuration.KeyValueInternalCollection' to type 'System.Configuration.AppSettingsSection'.

App.config:

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

  <extensions>
    <add key=".gif" value="image/gif"/>
    <add key=".png" value="image/png"/>
    <add key=".jpg" value="image/jpeg"/>
  </extensions>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
</configuration>

C# code:

AppSettingsSection section = (AppSettingsSection)ConfigurationManager.GetSection("extensions");
Console.WriteLine(section.Settings[".gif"].Value.ToString());

Upvotes: 2

Views: 1372

Answers (1)

Natsuki_Kato
Natsuki_Kato

Reputation: 157

Change the System.Configuration.AppSettingsSection to System.Configuration.NameValueSectionHandler and get the value by System.Collections.Specialized.NameValueCollection

Upvotes: 1

Related Questions