326

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
  • 846
  • 1
  • 9
  • 26
twal
  • 6,999
  • 17
  • 48
  • 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. – TheTechGuy 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

532

Try using the WebConfigurationManager class from the System.Web.Configuration namespace instead. For example:

string userName = WebConfigurationManager.AppSettings["PFUserName"]
TylerH
  • 20,799
  • 66
  • 75
  • 101
Hector Correa
  • 26,290
  • 8
  • 57
  • 73
  • 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
  • 1
    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
  • 23
    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
  • 1
    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
52
  var url = ConfigurationManager.AppSettings["ServiceProviderUrl"];
yogeswaran K
  • 2,278
  • 8
  • 29
  • 45
  • 1
    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
  • 1
    @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
  • 10,150
  • 3
  • 52
  • 76
6

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

Saber
  • 2,440
  • 1
  • 25
  • 40
4

Full Path for it is

System.Configuration.ConfigurationManager.AppSettings["KeyName"]
Siddhartha
  • 1,473
  • 14
  • 10
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

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
  • 36,626
  • 12
  • 31
  • 42
0

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

var strName= ConfigurationManager.AppSettings["stringName"];
sampathsris
  • 21,564
  • 12
  • 71
  • 98
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 A.
  • 5,261
  • 8
  • 25
  • 38
-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
  • 12,242
  • 4
  • 52
  • 53
Lee Smith
  • 6,339
  • 6
  • 27
  • 34