App.Config 中的自定义部分,ConfigurationManager 停止工作

Custom section in App.Config, ConfigurationManager stops working

我用 c# 创建了一个控制台应用程序,它从 App.config 读取信息。如果我在 appSettings 部分添加东西,我可以访问它们并且它有效,但是一旦我添加一些自定义部分我就无法从中读取任何内容。我正在使用 ConfigurationManager,并且包含了它的参考。 我的应用配置如下所示:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<appSettings>
    <add key="overwriteBackupFiles" value="False"/>
    <add key="path" value="c:\temp"/>
</appSettings>
<ImageFormatsINeed>
  <add key="type1" value="width=180&#38;height=180"></add>
  <add key="type2" value="width=220&#38;height=220"></add>
  <add key="type3" value="width=500&#38;height=500"></add>
</ImageFormatsINeed>
</configuration>

我正在尝试像这样访问这些信息:

string path = ConfigurationManager.AppSettings["path"];

var settings = ConfigurationManager.GetSection("ImageFormatsINeed");

当我没有 ImageFormatsINeed 部分时,我可以从 AppSettings 获取路径并且它正在运行。但是一旦我添加了 ImageFormatsINeed 部分,一切都停止了。

现在我的问题是如何在 app.config 中添加自定义部分使其正常工作,或者我应该从一些自定义 xml 文件或配置文件中读取我的 ImageInformation?

您必须使用标签 <configSections> at the top in your app.config, for this case you should use the type AppSettingsSection

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
    <configSections>
        <section  name="ImageFormatsINeed" type="System.Configuration.AppSettingsSection" />
    </configSections>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>        
    <appSettings>
        <add key="overwriteBackupFiles" value="False"/>
        <add key="path" value="c:\temp"/>
    </appSettings>
    <ImageFormatsINeed>
      <add key="type1" value="width=180&#38;height=180"></add>
      <add key="type2" value="width=220&#38;height=220"></add>
      <add key="type3" value="width=500&#38;height=500"></add>
    </ImageFormatsINeed>
    </configuration>

然后在您的 C# 代码中:

NameValueCollection settings_section = ConfigurationManager.GetSection("ImageFormatsINeed") as NameValueCollection;
Console.WriteLine(settings_section["type1"]);