Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 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 Reply

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!

(希望这可以帮助!)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...