简体   繁体   中英

ConfigurationManager.AppSettings in returning null

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

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, eg MainSettings.settings . You can then add an item, eg 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>

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.

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

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"] + "";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM