【问题标题】:System.InvalidCastException after adding customize section in app.config在 app.config 中添加自定义部分后 System.InvalidCastException
【发布时间】:2016-09-02 11:54:42
【问题描述】:

我想创建一个简单的部分而不自己编写任何类,我已阅读其他帖子并尝试构建我自己的部分,但是当我尝试获取我的部分时它会引发 System.InvalidCastException 异常。谁能告诉我如何解决它?谢谢!

异常信息:

HttpServer.exe 中出现“System.InvalidCastException”类型的未处理异常

附加信息:无法将“System.Configuration.KeyValueInternalCollection”类型的对象转换为“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#代码:

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

【问题讨论】:

    标签: c# app-config


    【解决方案1】:

    将 System.Configuration.AppSettingsSection 更改为 System.Configuration.NameValueSectionHandler 并通过以下方式获取值 System.Collections.Specialized.NameValueCollection

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-18
      • 2012-10-28
      • 1970-01-01
      • 1970-01-01
      • 2012-02-29
      • 2011-01-30
      • 2011-10-02
      • 2015-08-11
      相关资源
      最近更新 更多