22

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.

enter image description here

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 ?

Darren
  • 68,902
  • 24
  • 138
  • 144
Yasser Shaikh
  • 46,934
  • 46
  • 204
  • 281
  • 1
    Do you have multiple App.config files? Try debugging and have a look at the Key count in ConfigurationManager.AppSettings, if it displays 0 I would assume VS is not detecting your app config file. – Darren Mar 26 '12 at 12:25
  • I have single app.config, and I have attached a screen shot of my debug – Yasser Shaikh Mar 26 '12 at 12:26
  • Add the app config file to the main project and not in the class library assembly. – Darren Mar 26 '12 at 12:28
  • To check this what I am doing is... I have created a test project and I am calling one of the public methods defined in a class created in this class library. This class lib project has a single app.config. – Yasser Shaikh Mar 26 '12 at 12:29
  • I have two projects in my solution 1. Class library 2. Test project where do I add it ? – Yasser Shaikh Mar 26 '12 at 12:33

6 Answers6

27

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

Darren
  • 68,902
  • 24
  • 138
  • 144
  • I have two projects in my solution 1. Class library 2. Test project where do I add it ? – Yasser Shaikh Mar 26 '12 at 12:35
  • Found it ! Thanks to Darren I tried and added app.config to my test project and as I was typing in ConfigurationManager.AppSetting... my resharper again prompted me about which System.Configuration version 2.0 and 4.0 I remembered me taking 4.0 earlier while coding in my class project I went back and removed the 4.0 reference and added 2.0 one and now it works !! – Yasser Shaikh Mar 26 '12 at 12:42
  • my main project is just test project which I will not ship. Hence I want to attach corresponding app.config file to class library only. how can I do that? – NShiva Mar 07 '23 at 16:13
8

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];          
    }
}
Yasser Shaikh
  • 46,934
  • 46
  • 204
  • 281
Vijay Channe
  • 81
  • 1
  • 2
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();
        }
Community
  • 1
  • 1
civilator
  • 119
  • 4
2

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.

The champ
  • 21
  • 1
2

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.

DrCrazyApe
  • 21
  • 3
2

Solved

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

Read from App.config in a Class Library project

This is what code look likes

  1. App.config

enter image description here

  1. From Class Library

    enter image description here

jithin john
  • 552
  • 4
  • 12