Advertisement
Advertisement


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


Question

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?

2019/10/24
1
824
10/24/2019 12:25:09 PM

Accepted Answer

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.

2015/06/02
810
6/2/2015 6:25:08 PM


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;

See Managing Application Settings for more information.

2019/12/27

Right click on your class library, and choose the "Add References" option from the Menu.

And from the .NET tab, select System.Configuration. This would include the System.Configuration DLL file into your project.

2019/12/27

I'm using this, and it works well for me:

textBox1.Text = ConfigurationManager.AppSettings["Name"];
2019/10/24

Read From Config:

You'll need to add a reference to the configuration:

  1. Open "Properties" on your project
  2. Go to "Settings" Tab
  3. Add "Name" and "Value"
  4. Get Value with using following code:

    string value = Properties.Settings.Default.keyname;
    

Save to the configuration:

   Properties.Settings.Default.keyName = value;
   Properties.Settings.Default.Save();
2019/12/27

You must add a reference to the System.Configuration assembly to the project.

2019/12/27

Source: https://stackoverflow.com/questions/1189364
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]