Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Reading settings from app.config or web.config in .NET

I'm dealing with a C# class library that should have the option to peruse settings from the web.config or app.config file.
I've found that

ConfigurationSettings.AppSettings.Get("MySetting")


works, yet that code has been set apart as deprecated by Microsoft.

I've perused that I ought to utilize:

ConfigurationManager.AppSettings["MySetting"]


In any case, the System.Configuration.ConfigurationManager class doesn't appear to be accessible from a C# Class Library project.

What is the most ideal approach to do this?
by

3 Answers

akshay1995
You'll need to add a reference to System.Configuration in your project's references folder.

You should definitely be using the ConfigurationManager over the obsolete ConfigurationSettings.
RoliMishra
Update for .NET Framework 4.5 and 4.6; the following will no longer work:

string keyvalue = System.Configuration.ConfigurationManager.AppSettings["keyname"];


Now access the Setting class via Properties:

string keyvalue = Properties.Settings.Default.keyname;
sandhya6gczb
For a sample app.config file like below:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="countoffiles" value="7" />
<add key="logfilelocation" value="abc.txt" />
</appSettings>
</configuration>

You read the above application settings using the code shown below:

using System.Configuration;

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:

string configvalue1 = ConfigurationManager.AppSettings["countoffiles"];
string configvalue2 = ConfigurationManager.AppSettings["logfilelocation"];

Login / Signup to Answer the Question.