ConfigurationManager.AppSettings in returning null - c#

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

Related

C# console app can't read auxiliary App.config

I have a C# console app. It reads values from App.config.
Within App.config I make use of the file property of the appSettingssection.
In this way I can have a secondary configuration file that should supplement/overwrite properties defined in the primary configuration file.
However I find that the properties in the secondary file are not available at run time.
App.config (extract)
<appSettings file="App-not-in-source-control.config">
<add key="THIS_IS_A_TEST_KEY" value="Test Value" />
....
</appSettings>
App-not-in-source-control.config
<appSettings>
<add key="SOMEVALUE" value="foobar"/>
</appSettings>
Program.cs (Extract)
//THIS WORKS
var only4dbg = ConfigurationManager.AppSettings["THIS_IS_A_TEST_KEY"].ToString();
//THIS DOESNT WORK
var someValue = ConfigurationManager.AppSettings["SOMEVALUE"].ToString();
The attempt to read SOMEVALUE results in the following exception
Unhandled Exception: System.NullReferenceException:
Object reference not set to an instance of an object.
Is there something I've overlooked here ?
OK well having written that all out I realised what the problem was.
The secondary config file is only available to the run time if you've set the 'Copy to Output Directory' property of the file to something other than 'Never' ('Never' is the default setting).
It's strange to me that 'Never' is the default setting ; it's not the case for the 'App.config' and the secondary config (at least in my case) was created using the 'Add | New Item | Application Configuration File' dialog sequence within 'Solution Explorer' - there doesn't seem to be much point asking Visual Studio to create a config file which isn't going to be available to the project build output.
Regardless that's the way it is - hope this helps someone else.

Referenced DLL, in Web API project not reading dll.config nor web.config

This has been asked before, but I can't find an answer that works for me.
I have a solution that contains 5 projects, one is a Web API (.net 4.5) and one is a Class Library (.net 4.5). The Web API has a reference to the class/DLL. In the class project, the Settings.settings is utilized to enter values in the App.Config. All the values in the settings are Type string, Scope Application, Access Modifier Internal.
These values are created in the App.Config and look something like this:
<applicationSettings>
<xxxxx.Properties.Settings>
<setting name="setting1" serializeAs="String">
<value>1</value>
</setting>
<setting name="setting2" serializeAs="String">
<value>abc123</value>
</setting>....
In the class code, the values are read like so:
Properties.Settings.Default.setting1;
When the package for the Web API is created, it has the .dll, but not the .dll.config file. If I manually copy the .dll.config file, the .dll doesn't read from it. It also doesn't seem to read the ConnectionString fromt he web.config either.
I need the DLL to read either the .dll.config or the Web APIs web.config file. I have tried several solutions posted in stackoverflow, but most seem updated/deprecated and/or throw errors when I tried them.
What is the current and correct approach to this issue, with .net 4.5?
Thanks
I ended up deleting everything from the Settings.settings eliminating the
<applicationSettings>
<xxxxx.Properties.Settings>...
section of the App.Config. Then I just added a regular <appSettings> section and calling the value in code with
ConfigurationManager.AppSettings["xxxxx"];
I read in some posts that this was no longer supported, but it was the method that worked for me.

App.config - Values in <applicationSettings> fail, Values in <appSettings> work

In an effort to try to get ConfigurationManager.AppSettings[..] working again, I've created one applicationSettings element and one appSettings element in a single-project console application.
<applicationSettings>
<el_testo.Properties.Settings>
<setting name="ApplicationSetting" serializeAs="String">
<value>Application Value</value>
</setting>
</el_testo.Properties.Settings>
</applicationSettings>
<appSettings>
<add key="AppSetting" value="App Value"/>
</appSettings>
Here's my effort to retrieve the two values.
Debug.WriteLine("---> ApplicationSettings Test");
Debug.WriteLine(ConfigurationManager.AppSettings["ApplicationSetting"] + "");
var applicationSettingsTest = ConfigurationManager.AppSettings["ApplicationSetting"];
Debug.WriteLine(applicationSettingsTest);
Debug.WriteLine("---> AppSettings Test");
Debug.WriteLine(ConfigurationManager.AppSettings["AppSetting"]);
Debug.WriteLine("---> Complete");
And here are my results.
---> ApplicationSettings Test
---> AppSettings Test
App Value
---> Complete
I could just "settle" and use the appSettings construct. It would be kind of nice, however, to use the Settings tab on Project properties on this project and future projects. Here's what I've tried this far to make work.
There's only one project in this application. Therefore, I can't be setting the value in one project and trying to read it in another. (Additionally, appSettings works.)
I verified that the project includes the assembly reference System.Configuration and the class includes the proper namespace reference (using System.Configuration;)
I've double-checked spelling and case of the setting name in ConfigurationManager.AppSettings["ApplicationSetting"].
I've tried linking App.config to different XML Schema files, EnterpriseLibrary.Configuration.xsd and an XML Schema file I generated using the XML menu in Visual Studio.
I've wiped the contents of the Debug and Release folders and rebuilt the project.
You are incorrectly trying to read your ApplicationSetting element as a key under appSettings with the following statement:
ConfigurationManager.AppSettings["ApplicationSetting"]
This means your are trying to get the value of this:
<appSettings>
<add key="ApplicationSetting" value="xxxx" />
</appSetting>
Instead; when you add an application setting using the project properties, it creates a settings class extending the ApplicationSettingsBase class, create properties with the name of your settings and will also add necessary configSection and a default config element in your app.config file. Why not just create and use that class which will give you type strict access to your application settings?
Just go to Project/e_testo Properties/Settings and add ApplicationSetting with scope Application
You can then access the ApplicationSetting by
var applicationSettingsTest = Properties.Settings.Default.ApplicationSetting

How does AppSettings in VB.NET windows Forms work?

Hello I have build a small app to demo a concept in C# in which I added the application config file etc added System.Configuration dll to the reference and accessed the settings:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="username" value="myknownusername"/>
</appSettings>
</configuration>
No news It worked flawlessly with the code:
private String username = ConfigurationManager.AppSettings["username"];
Now I have been asked to do the port the app to VB.NET and to my biggest surprise. It's been a while that I opened visual studio in VB.NET project. I was surprised to see an already white dashed App.config file so I added my AppSettings section and after 3 hours I still can't get the value of the username using the same ConfigurationManager
Dim username as String = ConfigurationManager.AppSettings("username")
I have included another application configuration app1.config which by the way has generated entries already. I could not get anything with the app1.config either.It also returns Nothing
</sharedListeners>
</system.diagnostics>
</configuration>
I am really perplexed as how a simple reading of configuration file could be this challenging in VB.NET unless I am using the wrong method which I always use in C#.
Kindly point me to whatever I am not doing right.
EDIT
As you can see in the picture below, I have all it needs to work properly.I as expecting to read the setting key from either App.config or app1.config. When I run like shown below the MessageBox is empty
I found the culprit, I needed to right click the generated App.config and choose Include In Project. that's it. it's weird because I never do that in a C# project.

How to separate configuration file?

I have a .net solution having a reference hierarchy like this
MyWinApp->ServerCore->DataAccess
where the last two are class libraries and myWinApp is a windows app.
Now, each time I want to run this project on different servers I need to rebuild the project since I couldn't manage to separate the configuration file(app.config) of DataAccess project that has connection string related configurations.
How can I separate database configurations from the application code? I tried to build action options but it doesn't work :S What might be the most feasible solution?
Thanks in advance
The configuration should most likely go with the MyWinApp project. The configuration file goes with what is executing. So if you make an installer for your application, it'll have a configuration file called MyWinApp.exe.config that was created from your App.Config.
Basically the app.config with your Datalayer.dll doesn't really do much.
What you might want to do is look at how the configSource property works for configuration files in .net here: http://msdn.microsoft.com/en-us/library/system.configuration.sectioninformation.configsource.aspx and see if this is what you're looking for. This lets you set a configSource for your connection strings that you can change per machine.
All I do is setup a simple xcopy before a deploy and I have the correct configuration settings before deploying an asp.net app. If you have to package an installer, copying the correct files before building the installer should do the trick as well.
For my DAL projects I typically have a DataLayer.dll.config file but I actually add the ConnectionString entries to my Program.exe.config file. I don't know that you need anything special for this. Possibly just reference a static readonly string or something from the DataLayer.dll in the Program.exe?
Or, do you really want to have separate configuration files? If so then you can use the ConfigurationManager class to open a loose configuration file with the OpenMappedMachineConfiguration method. See MSDN ref here: http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.openmappedmachineconfiguration.aspx
I think you can use applicationSettings to include configuration for specific referenced assemblies:
For example:
<configuration>
<applicationSettings>
<ProjectName.Properties.Settings>
<setting name="ConnectionString" serializeAs="String">
<value>YourConnectionStringHere</value>
</setting>
</ProjectName.Properties.Settings>
</applicationSettings>
</configuration>
Where "ProjectName" is the name of the reference you need to configure. Each project can have it's own app.config with the above applicationSettings entry and a value specific to the project itself.

Categories

Resources