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.
Does anyone know what the best way to do this is?
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
.
For Sample App.config 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 app settings using 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"];
Hope this helps!
Update for 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.
链接地址: http://www.djcxy.com/p/3572.html上一篇: 我如何获得代码所在的程序集路径?