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
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
works, but that code has been marked as deprecated by Microsoft.
I've read that I should be using:
System.Configuration.ConfigurationManager class doesn't seem to be available from a C# Class Library project.
What is the best way to do this?
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
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:
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"];
Read more... Read less...
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.
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.
I'm using this, and it works well for me:
textBox1.Text = ConfigurationManager.AppSettings["Name"];
Read From Config:
You'll need to add a reference to the configuration:
- Open "Properties" on your project
- Go to "Settings" Tab
- Add "Name" and "Value"
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();
You must add a reference to the System.Configuration assembly to the project.