简体   繁体   中英

Read from App.config in a Class Library project

I am developing a simple class library project, which will give me a dll.

I wanted a particular value to be read from a config file. So I have added an App.config file to my project.

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

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

  </configuration>

Above is my App.config file, and now I am trying to read it as following

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

But I am not getting any value in my string variable.

在此输入图像描述

I had done this for a web application in a similar way and it worked. But somehow I am not able to get this working.

Is the idea of having App.config in a class library project correct in the first place ?

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

You dont need to add app.config file. If you create class library for web based application then you can fetch connection string directly from web.config file

OR

You can add any text file with connection string in it and fetch that string . using this

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

assuming the question is asking for a config file specific to the dll project, not the app or web app project's config file, I used the following code to get the values from keys in the "sqlSection" section. (one caution is that this config file - even when it is set to copy always- is not automatically copied on a partial build of a web app. so I used the awesome one-line pre-build action to copy the file over, as mentioned in this post https://stackoverflow.com/a/40158880/1935056 ).

here is the entire dll config file

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


<sqlSection>

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

this is the c# code.

 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();
        }

My code to read the configuration file

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

example for my app.config file

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

If your solution has multiple projects listed, make sure the app settings are in the start up project, else you will be getting null as answer.

Access App.Config from Executeable in Class Library project.

Project 1: Sample (executeable project .exe)

Project 2: Sample.Database (class library project .dll)

Project 1 contains the 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>

Project 2 needs access to the Configuration Settings... Create following classes:

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;
    }
}

Static Class in dll Project:

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

Usage anywhere in class library project:

var xx = DBConnection.ConnectionStringLocal;

If you don't want to read the Connection String on every function call, create a member variable in DBConnection and set it when it is null, otherwise return it.

Solved

I have encountered this issue. What I did is below.

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

This is what code look likes

  1. App.config

在此输入图像描述

  1. From Class Library

    在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM