Read from App.config in a Class Library project

馋奶兔 提交于 2019-11-27 06:37:49

问题


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 ?


回答1:


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




回答2:


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



回答3:


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



回答4:


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.




回答5:


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.




回答6:


Solved

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

This is what code look likes

  1. App.config

  1. From Class Library



来源:https://stackoverflow.com/questions/9871948/read-from-app-config-in-a-class-library-project

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