How to read values from custom section in web.config

C#.NetWeb Config.Net 2.0

C# Problem Overview


I have added a custom section called secureAppSettings to my web.config file:

<configuration>
  <configSections>
    <section name="secureAppSettings" type="System.Configuration.NameValueSectionHandler, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  </configSections>
  <secureAppSettings>
    <add key="userName" value="username"/>
    <add key="userPassword" value="password"/>
  </secureAppSettings>  
</configuration>

secureAppSettings is decrypted and has two keys inside it.

Now in my code, I tried to access the keys like this:

string userName = System.Configuration.ConfigurationManager.secureAppSettings["userName"];
string userPassword = System.Configuration.ConfigurationManager.secureAppSettings["userPassword"];

But null is returning for these fields.

How can I get the field values?

C# Solutions


Solution 1 - C#

You could access them as key/value pairs:

NameValueCollection section = (NameValueCollection)ConfigurationManager.GetSection("secureAppSettings");
string userName = section["userName"];
string userPassword = section["userPassword"];

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionManoj SinghView Question on Stackoverflow
Solution 1 - C#Darin DimitrovView Answer on Stackoverflow