Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConfigurationManager.AppSettings in returning null

Tags:

c#

.net

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

like image 230
Hassan Mokdad Avatar asked Jul 07 '11 06:07

Hassan Mokdad


People also ask

What is ConfigurationManager appSettings?

it is a .net builtin mechanism to define some settings before the application starts, without recompiling. see msdn configurationmanager.

Can I use ConfigurationManager in .NET core?

ConfigurationManager was added to support ASP.NET Core's new WebApplication model, used for simplifying the ASP.NET Core startup code.

Where do I put appSettings in web config?

Locate the web. config file in the root directory of your application (or create one if it does not already exist). Add an <appSettings> element. Add <add> child elements along with key / value pairs to the <appSettings> element as required.

What is the namespace for ConfigurationManager in C#?

Namespace: System.Configuration To use the ConfigurationManager class, your project must reference the System. Configuration assembly. By default, some project templates, like Console Application, do not reference this assembly so you must manually reference it.


2 Answers

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>
like image 165
Adam Ralph Avatar answered Sep 20 '22 08:09

Adam Ralph


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.
like image 30
Stuart Helwig Avatar answered Sep 22 '22 08:09

Stuart Helwig