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:14

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

查看更多
神经病院院长
3楼-- · 2019-01-03 01:17

Try this:

string keyvalue=System.Configuration.ConfigurationManager.AppSettings["keyname"];

In web.config should be next structure:

<configuration>
<appSettings>
<add key="keyname" value="keyvalue" />
</appSettings>
</configuration>
查看更多
霸刀☆藐视天下
4楼-- · 2019-01-03 01:19

Im using this and it works well for me

textBox1.Text = ConfigurationManager.AppSettings["Name"];
查看更多
贼婆χ
5楼-- · 2019-01-03 01:19

Read From Config :

You'll need to add a reference to Config

  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 Config :

   Properties.Settings.Default.keyName = value;
   Properties.Settings.Default.Save();
查看更多
Animai°情兽
6楼-- · 2019-01-03 01:19

Also, you can use formo:

Config:

<appSettings>
    <add key="RetryAttempts" value="5" />
    <add key="ApplicationBuildDate" value="11/4/1999 6:23 AM" />
</appSettings>

Code:

dynamic config = new Configuration();
var retryAttempts1 = config.RetryAttempts;                 // returns 5 as a string
var retryAttempts2 = config.RetryAttempts(10);             // returns 5 if found in config, else 10
var retryAttempts3 = config.RetryAttempts(userInput, 10);  // returns 5 if it exists in config, else userInput if not null, else 10
var appBuildDate = config.ApplicationBuildDate<DateTime>();
查看更多
姐就是有狂的资本
7楼-- · 2019-01-03 01:19

Another possible solution:

var MyReader = new System.Configuration.AppSettingsReader();
string keyvalue = MyReader.GetValue("keyalue",typeof(string)).ToString();
查看更多
登录 后发表回答