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

问题描述 投票:15回答:6

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

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

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

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

  </configuration>

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

  string strVal = System.Configuration.ConfigurationManager.AppSettings["serviceUrl"];

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

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

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

c# .net app-config class-library
6个回答
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];          
    }
}

2
投票

假设问题是要求特定于dll项目的配置文件,而不是应用程序或Web应用程序项目的配置文件,我使用以下代码从“sqlSection”部分中的键获取值。 (需要注意的是,这个配置文件 - 即使设置为始终复制 - 也不会自动复制到Web应用程序的部分版本上。所以我使用了令人敬畏的单行预构建操作来复制文件,如在这篇文章中提到https://stackoverflow.com/a/40158880/1935056)。

这是整个dll配置文件

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


<sqlSection>

<add key="sql1" value="--statement--"/>
</sqlSection>

这是c#代码。

 string GetSqlStatement(string key)
    {
            string path =   Path.GetDirectoryName(Assembly.GetCallingAssembly().CodeBase) + @"\DataLayer.dll.config";

        XDocument doc = XDocument.Load(path);

        var query = doc.Descendants("sqlSection").Nodes().Cast<XElement>().Where(x => x.Attribute("key").Value.ToString() == key).FirstOrDefault();

        if (query != null)
        {
            return query.Attribute("value").Value.ToString();
        }

1
投票

我的代码读取配置文件

Int32 FilesCountLimit = Convert.ToInt32(ConfigurationManager.AppSettings["FilesTotalCount"]);
    long FilesLengthLimit = Convert.ToInt64(ConfigurationManager.AppSettings["FilesTotalSize"]);

我的app.config文件的示例

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="FilesTotalCount" value="1000" />
    <add key="FilesTotalSize" value="500000000" />
  </appSettings>
</configuration>

如果您的解决方案列出了多个项目,请确保应用程序设置在启动项目中,否则您将获得null作为答案。


1
投票

从类库项目中的可执行文件访问App.Config。

项目1:示例(可执行项目.exe)

项目2:Sample.Database(类库项目.dll)

项目1包含app.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
  </startup>
  <connectionStrings>
    <clear />
    <add name="Connection_Local" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\work\WF\ScaleCalibration\ScaleCalibration\AppData\db_local.mdf;Integrated Security=True;Connect Timeout=30" />
  </connectionStrings>>
</configuration>

项目2需要访问配置设置...创建以下类:

public class AssemblyConfiguration : MarshalByRefObject
{
    public static string GetConnectionString(string name)
    {
        Assembly callingAssembly = Assembly.GetEntryAssembly();
        var conStringCollection = ConfigurationManager.OpenExeConfiguration(callingAssembly.Location).ConnectionStrings;
        return conStringCollection?.ConnectionStrings[name].ConnectionString;
    }
}

dll项目中的静态类:

public static class DBConnection
{
    public static string ConnectionStringLocal => AssemblyConfiguration.GetConnectionString("Connection_Local");
}

在类库项目中的任何位置使用:

var xx = DBConnection.ConnectionStringLocal;

如果您不想在每次函数调用时读取连接字符串,请在DBConnection中创建一个成员变量,并在它为null时设置它,否则返回它。


0
投票

解决了

我遇到过这个问题。我在下面做了什么。

Read from App.config in a Class Library project

这就是代码看起来喜欢的东西

  1. App.config中

enter image description here

  1. 从类库 enter image description here
© www.soinside.com 2019 - 2024. All rights reserved.