Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

What is the best way to do this?

like image 970
Russ Clark Avatar asked Jul 27 '09 16:07

Russ Clark


People also ask

Is app config the same as web config?

Web. Config is used for asp.net web projects / web services. App. Config is used for Windows Forms, Windows Services, Console Apps and WPF applications.

How read app config file in VB NET?

You can mark the settings as public in the C# project ("Access Modifier" in the property pane of settings) and then you can access it from the vb project (don't forget to add the reference).

What is the use of app config in C#?

App. Config is an XML file that is used as a configuration file for your application. In other words, you store inside it any setting that you may want to change without having to change code (and recompiling). It is often used to store connection strings.


2 Answers

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.

like image 31
womp Avatar answered Sep 19 '22 13:09

womp


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"]; 
like image 155
Ram Avatar answered Sep 19 '22 13:09

Ram