c# - 在 app.config 中添加自定义部分后出现 System.InvalidCastException

标签 c# app-config

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

异常信息:

HttpServer.exe 中发生类型为“System.InvalidCastException”的未处理异常

附加信息:无法将“System.Configuration.KeyValueInternalCollection”类型的对象转换为类型“System.Configuration.AppSettingsSection”。

应用程序配置:

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

最佳答案

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

关于c# - 在 app.config 中添加自定义部分后出现 System.InvalidCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39283319/

相关文章:

c# - 是否可以取消选择 RadioButton 组中的所有值?

c# - 如何将 ReadOnlyCollection<T> 转换为 T[]?

c# - 将 ContentControl *放在 * WPF DataTemplate 中?

c# - 如何将用户的消息存储在表存储中? (微软机器人框架 SDK4 和 C#)

c# - 将 app.config 配置部分重新定位到 AppData 文件夹

.net - 跟踪监听器忽略traceOutputOptions ="DateTime"

c# - 从 API 上传时如何设置 FileName 值?

c# - 使用 EntityFramework 源项目而不是其程序集的解决方案无法成功启动

.net - 安全、可移植的加密配置值——可能吗?

visual-studio-2010 - Visual Studio 总是为 App.config 选择错误的 xsd