1
votes

I have created a console app in c# that reads information from App.config. if i add things in appSettings section, i can acces them and it works, but as soon as i add some custom sections i cant read anything from it. I am using ConfigurationManager, and i have the reference for it included. My app config looks like this:

<?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>

and i am trying to acces those information like this:

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

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

When i didnt have the ImageFormatsINeed section i could get the path from AppSettings and it was working. But as soon as i added my ImageFormatsINeed section, everything stops working.

Now my question is how can i add custom sections in app.config that it will work, or should i just read my ImageInformation from some custom xml file or config file?

1

1 Answers

2
votes

You have to use the tag <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>

Then in your C# code:

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