Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

c# - 在.NET中从app.config或web.config读取设置(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).

(我正在使用一个C#类库,该类需要能够从web.configapp.config文件中读取设置(取决于DLL是从ASP.NET Web应用程序还是Windows Forms应用程序引用的)。)

I've found that

(我发现)

ConfigurationSettings.AppSettings.Get("MySetting")

works, but that code has been marked as deprecated by Microsoft.

(可以,但是该代码已被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.

(但是,C#类库项目中似乎没有System.Configuration.ConfigurationManager类。)

What is the best way to do this?

(做这个的最好方式是什么?)

  ask by Russ Clark translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For Sample App.config like below:

(对于如下所示的示例App.config:)

<?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.

(如果还没有引用,则可能还需要在项目中添加对System.Configuration的引用。)

You can then access the values like so:

(然后,您可以像这样访问这些值:)

string configvalue1 = ConfigurationManager.AppSettings["countoffiles"];
string configvalue2 = ConfigurationManager.AppSettings["logfilelocation"];

Hope this helps!

(希望这可以帮助!)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...