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, 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>
Hard to say from what you've provided here:
- Check your spelling of the value in myKey
- 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"] + "";
精彩评论