I'm working on a C# class library that needs to be able to read settings from the web.config
or app.config
file (depending on whether the DLL is referenced from an ASP.NET web application or a Windows Forms application).
I've found that
ConfigurationSettings.AppSettings.Get("MySetting")
works, but that code has been marked as deprecated by Microsoft.
I've read that I should be using:
ConfigurationManager.AppSettings["MySetting"]
However, the System.Configuration.ConfigurationManager
class doesn't seem to be available from a C# Class Library project.
Does anyone know what the best way to do this is?
For Sample App.config like below:
You read the above app settings using code shown below:
You may also need to also add a reference to
System.Configuration
in your project if there isn't one already. You can then access the values like so:Hope this helps!
Pls check .net version you are working. It should be higher than 4. And you have to add System.Configuration system library to your application
I strongly recommend you to create a Wrapper for this call. Something like a
ConfigurationReaderService
and use dependency injection to get this class. This way you will be able to isolate this configuration files for test purposes.So use the
ConfigurationManager.AppSettings["something"];
suggested and return this value. You can with this method create some kind of default return if there is no key available in .config file.Right click on your class Library, and choose the "Add References" option from the Menu; and finally from the .NET tab, select System.Configuration. This would include System.Configuration dll into your project.
Just for completeness, there's another option available for web projects only:
The benefit of this is that it doesn't require an extra reference to be added so may be preferable for some people.
Update for framework 4.5 and 4.6; the following will no longer work:
Now access the Setting class via Properties:
See Managing Application Settings for more information.