Read from App.config in a Class Library project

梦想的初衷 提交于 2019-11-28 11:58:22

As stated in my comment, add the App.Config file to the main solution and not in the class library project.

Vijay Channe

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

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.

This is what code look likes

  1. App.config

  1. From Class Library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!