在.NET中从app.config或web.config阅读设置

9 浏览
0 Comments

在.NET中从app.config或web.config阅读设置

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

我发现

ConfigurationSettings.AppSettings.Get("MySetting")

有效,但是该代码已经被Microsoft标记为不推荐使用。

我已经阅读过应该使用以下代码:

ConfigurationManager.AppSettings["MySetting"]

然而,在一个C#类库项目中,System.Configuration.ConfigurationManager类似乎不可用。

最好的方法是什么?

admin 更改状态以发布 2023年5月23日
0
0 Comments

您需要在项目的引用文件夹添加对System.Configuration的引用

您应该绝对使用已过时的ConfigurationSettings而不是ConfigurationManager

0
0 Comments

针对下面的示例app.config文件:



  
    
    
  

您可以使用以下代码读取上述应用程序设置:

using System.Configuration;

如果项目中尚未引用System.Configuration,您可能还需要添加一个引用。然后,您可以按以下方式访问这些值:

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

0