从类库项目中的App.config中读取

Yas*_*ser 16 .net c# app-config class-library

我正在开发一个简单的类库项目,它将给我一个DLL.

我想从配置文件中读取特定值.所以我在我的项目中添加了一个App.config文件.

 <?xml version="1.0" encoding="utf-8" ?>
 <configuration>

  <appSettings>
  <add key="serviceUrl" value="test value" />
  </appSettings>

  </configuration>
Run Code Online (Sandbox Code Playgroud)

上面是我的App.config文件,现在我正在尝试将其读取如下

  string strVal = System.Configuration.ConfigurationManager.AppSettings["serviceUrl"];
Run Code Online (Sandbox Code Playgroud)

但是我的字符串变量没有任何值.

在此输入图像描述

我以类似的方式为Web应用程序完成了这项工作.但不知怎的,我无法让这个工作.

是否首先在类库项目中使用App.config是正确的?

Dar*_*ren 18

如我的评论中所述,将App.Config文件添加到主解决方案而不是类库项目中.


小智 6

您不需要添加app.config文件.如果为基于Web的应用程序创建类库,则可以直接从web.config文件获取连接字符串

要么

您可以在其中添加任何带有连接字符串的文本文件并获取该字符串.用这个

public static ConnectionStringSettings ConnSettings
{
    get
    {
        string connectionStringKey = null;
        connectionStringKey = ConfigurationManager.AppSettings.Get("DefaultConnectionString");
        return ConfigurationManager.ConnectionStrings[connectionStringKey];          
    }
}
Run Code Online (Sandbox Code Playgroud)