319

I am trying to read the keys from the Web.config file in a different layer than the web layer (Same solution)

Here is what I am trying:

string userName = System.Configuration.ConfigurationManager.AppSettings["PFUserName"];
string password = System.Configuration.ConfigurationManager.AppSettings["PFPassWord"];

And here is my appSettings in the Web.config file:

<configuration>
   ....
   <appSettings>
      <add key="PFUserName" value="myusername"/>
      <add key="PFPassWord" value="mypassword"/>
   </appSettings>
   ....
</configuration>

When I debug the code username and password are just null, so it is not getting the value of the keys.

What am I doing wrong to read these values?

Max
  • 796
  • 1
  • 8
  • 26
twal
  • 6,899
  • 16
  • 46
  • 58
  • How is this second project being accessed by your website? – Dan Atkinson Jan 04 '11 at 15:40
  • 14
    **Your syntax is correct**. You probably edited the wrong web.config file that's why it returns `NULL`. Late comment but no one pointed this out. – Hammad Khan Jan 08 '14 at 17:59
  • 1
    That's what happened to me, I was in the Views web.config. – JQII Apr 24 '14 at 19:08
  • 1
    Only the Web project has access to the System.Configuration.ConfigurationManager.AppSettings object. Other layers cannot access this object as they do not implement System.Web. – Hashim Akhtar Feb 11 '16 at 17:18

10 Answers10

521

Try using the WebConfigurationManager class instead. For example:

string userName = WebConfigurationManager.AppSettings["PFUserName"]
dav_i
  • 26,475
  • 17
  • 99
  • 133
Hector Correa
  • 25,772
  • 7
  • 56
  • 70
  • 2
    Thanks for your answer, I tried as you recommended and still get the same result. I actually now get a NullReferenceException on the ToString() – twal Jan 04 '11 at 15:37
  • If you get a null exception it means that is not finding the setting. Try doing something like this: "object x = WebConfigurationManager.AppSettings["PFUserName"];" and you probably will get a null value which means that it is not finding the requested setting. – Hector Correa Jan 04 '11 at 15:46
  • 22
    Are you sure the settings are on the correct web.config? (I've made the mistake before of dumping my values in the web.config under the "Views" folder and lost a ton of time troubleshooting why it's not working as expected. – Hector Correa Jan 04 '11 at 15:47
  • 4
    Thank you, You can drop the ToString because AppSettings indexer already return string. – Ido Ran Feb 10 '13 at 10:36
  • I don't think *ToString* is needed to be explicitly called. The return type from the bracketification **is** *String* already, isn't it? It looks to me like *"string".ToString()* - which, although technically correct, is a bit superfluous. – Konrad Viltersten May 30 '14 at 03:57
49
  var url = ConfigurationManager.AppSettings["ServiceProviderUrl"];
yogeswaran K
  • 2,210
  • 7
  • 29
  • 45
  • 13
    Right answer. `ToString()` is redundant though. – anar khalilov Nov 13 '13 at 09:44
  • 9
    ToString can be dangerous if the value isn't in the app config. Better to trap the object returned and test for null before resolving. Try running it when "mysettings" isn't in the config and you'll see the exception pop. Instead something like whats below might be safer... string key = "mysettings"; string value = ConfigurationManager.AppSettings[key]; if ( value == null ) value = "unknown value"; – Joe Healy Mar 22 '15 at 17:59
  • 1
    true there is no need for the .ToString() since it is a string – Rola Jan 05 '16 at 11:36
  • 2
    @JoeHealy You can shorten that and increase clarity with the null coalescing operator: `string value = ConfigurationManager.AppSettings[key] ?? "unknown value"` – Zenexer Aug 31 '16 at 00:14
  • I am wondering what is the difference between this answer and the code in OP's question! Are they not the same? – user1451111 Dec 09 '19 at 00:31
  • @user1451111, at its current state, yes, this answer's code is identical to the OP's code. At first, the answer was slightly different, and [suggested](https://stackoverflow.com/posts/17148499/edit/016b7b38-bb60-4ed5-bb11-d998f47e53fb) to call `ToString()`, although that shouldn't have mattered anyway, because as [commented under the OP's question](https://stackoverflow.com/questions/4595288/reading-a-key-from-the-web-config-using-configurationmanager#comment31564129_4595288), the syntax is already correct. – OfirD Feb 13 '22 at 14:32
6

I found this solution to be quite helpful. It uses C# 4.0 DynamicObject to wrap the ConfigurationManager. So instead of accessing values like this:

 WebConfigurationManager.AppSettings["PFUserName"]

you access them as a property:

dynamic appSettings = new AppSettingsWrapper();
Console.WriteLine(appSettings.PFUserName);  

EDIT: Adding code snippet in case link becomes stale:

public class AppSettingsWrapper : DynamicObject
{
     private NameValueCollection _items;

    public AppSettingsWrapper()
    {
        _items = ConfigurationManager.AppSettings;
    }

     public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        result = _items[binder.Name];
        return result != null;
    }
}
mateuscb
  • 9,130
  • 3
  • 48
  • 75
6

If the caller is another project, you should write the config in caller project not the called one.

Saber
  • 2,082
  • 1
  • 21
  • 38
3

Full Path for it is

System.Configuration.ConfigurationManager.AppSettings["KeyName"]
Siddhartha
  • 1,297
  • 12
  • 10
2

There will be two Web.config files. I think you may have confused with those two files.

Check this image:

click this link and check this image

In this image you can see two Web.config files. You should add your constants to the one which is in the project folder not in the views folder

Hope this may help you

sticky bit
  • 35,543
  • 12
  • 29
  • 39
1

This issue happens if this project is being used by another project. Make sure you copy the app setting keys to the parent project's app.config or web.config.

1

Also you can try this line to get string value from app.config file.

var strName= ConfigurationManager.AppSettings["stringName"];
sampathsris
  • 20,518
  • 11
  • 61
  • 93
0

with assuming below setting in .config file:

<configuration>
   <appSettings>
     <add key="PFUserName" value="myusername"/>
     <add key="PFPassWord" value="mypassword"/>
   </appSettings> 
</configuration>

try this:

public class myController : Controller
{
    NameValueCollection myKeys = ConfigurationManager.AppSettings;

    public void MyMethod()
    {
        var myUsername = myKeys["PFUserName"];
        var myPassword = myKeys["PFPassWord"];
    }
}
Aiyoub
  • 5,023
  • 7
  • 24
  • 35
-5

Sorry I've not tested this but I think it's done like this:

var filemap = new System.Configuration.ExeConfigurationFileMap();            
System.Configuration.Configuration config =  System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(filemap, System.Configuration.ConfigurationUserLevel.None);

//usage: config.AppSettings["xxx"]
Nima Soroush
  • 11,086
  • 4
  • 50
  • 51
Lee Smith
  • 5,961
  • 6
  • 26
  • 33