Reading settings from app.config or web.config in

2019-01-03 01:03发布

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?

20条回答
甜甜的少女心
2楼-- · 2019-01-03 01:05

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!

查看更多
三岁会撩人
3楼-- · 2019-01-03 01:10

Pls check .net version you are working. It should be higher than 4. And you have to add System.Configuration system library to your application

查看更多
混吃等死
4楼-- · 2019-01-03 01:11

I strongly recommend you to create a Wrapper for this call. Something like a ConfigurationReaderService and use dependency injection to get this class. This way you will be able to isolate this configuration files for test purposes.

So use the ConfigurationManager.AppSettings["something"]; suggested and return this value. You can with this method create some kind of default return if there is no key available in .config file.

查看更多
霸刀☆藐视天下
5楼-- · 2019-01-03 01:12

Right click on your class Library, and choose the "Add References" option from the Menu; and finally from the .NET tab, select System.Configuration. This would include System.Configuration dll into your project.

查看更多
霸刀☆藐视天下
6楼-- · 2019-01-03 01:12

Just for completeness, there's another option available for web projects only:

System.Web.Configuration.WebConfigurationManager.AppSettings["MySetting"]

The benefit of this is that it doesn't require an extra reference to be added so may be preferable for some people.

查看更多
太酷不给撩
7楼-- · 2019-01-03 01:13

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.

查看更多
登录 后发表回答