52

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?

plr108
  • 1,201
  • 11
  • 16
Manoj Singh
  • 7,569
  • 34
  • 119
  • 198
  • most useful and always working solution is this one in my opinion: http://stackoverflow.com/a/28600293/4250041 – benraay Mar 07 '17 at 13:32

1 Answers1

68

You could access them as key/value pairs:

NameValueCollection section = (NameValueCollection)ConfigurationManager.GetSection("secureAppSettings");
string userName = section["userName"];
string userPassword = section["userPassword"];
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 2
    it is seperate section than appsettings, this is the new section called "secureAppSettings", how can I get the values in appsettings and also "secureAppSettings" is encrpted now. – Manoj Singh Jun 13 '11 at 10:18
  • 3
    @Manu, sorry I totally misread your question, you are right. I've updated my answer with the correct way of reading those values. – Darin Dimitrov Jun 13 '11 at 10:22
  • 1
    @DarinDimitrov: Is this read-only? Is there a way to set the value? – Yi Zeng Aug 16 '13 at 01:43
  • 3
    @user1177636, yes it's readonly. In a web application it is bad practice to modify web.config as this would result in your application being restarted. Use a database or another persistent storage for this purpose. – Darin Dimitrov Aug 18 '13 at 17:59