14

I am using ConfigurationManager.AppSettings[myKey] to read a value from the app.config file in my windows application, but the value returned is always null, even though the key exists and it has a value, Deas any one know why?

Thanks

Hassan Mokdad
  • 5,832
  • 18
  • 55
  • 90

4 Answers4

25

One, perhaps easier, alternative is to use a Settings file. This encapsulates the creation and maintenance of App.config values in a designer GUI and generates code for accessing the values.

To add a Settings file, right click your project in VS and click 'Add -> New Item', select 'Settings file' and give it a meaningful name, e.g. MainSettings.settings. You can then add an item, e.g. Foo, specify whether it is application or user-wide, define it's type and a assign it a value. In your code you can retreive the value by simple writing MainSettings.Default.Foo.

After compilation, you can change the value by editing the config file. The setting will appear as follows:-

<applicationSettings>
    <YourNamespace.MainSettings>
        <setting name="Foo" serializeAs="String">
            <value>Bar</value>
        </setting>
    </YourNamespace.MainSettings>
</applicationSettings>
Adam Ralph
  • 29,453
  • 4
  • 60
  • 67
9

Hard to say from what you've provided here:

  1. Check your spelling of the value in myKey
  2. Ensure you are looking at the right app.config - if this call is in a referenced library and you're expecting a value to come from the calling project's app.config, but your library has an app.config for some reason it may be causing your problem.
Chris
  • 5,876
  • 3
  • 43
  • 69
Stuart Helwig
  • 9,318
  • 8
  • 51
  • 67
  • I actuallay have only one app.config file, and I am just calling ConfigurationManager.AppSettings[myKey], and the key exists! not sure whay this is happening – Hassan Mokdad Jul 07 '11 at 06:30
  • 1
    ConfigurationManager.AppSettings[myKey] is [case-insensitive](https://stackoverflow.com/questions/3295293/how-to-check-if-an-appsettings-key-exists#comment49367267_6071115); just edited this answer. – Chris Jul 06 '17 at 17:30
0

i have two project in my solution first i add app.config file in class library project which all instances is call from console application i added these entries in config file in class lib project

<appSettings> 
<add key="userName" value="user2" /> 
<add key="emilsLimit" value="50" /> 
</appSettings>

it was throwing null exception when i get these in a class in class library project but when i delete app.config from class Library project and added in Console project it works.Cheers

Note: Class lib project reference is added in console

zaheer ahmad
  • 294
  • 4
  • 16
-1

I was having the same problem, but when I added an empty string ( + "") on the end it picks up the string in the appsettings

for example

string s = ConfigurationManager.AppSettings["myKey"] + "";
beaumondo
  • 4,862
  • 7
  • 29
  • 42