Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read from App.config in a Class Library project

Tags:

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 ?

like image 770
Yasser Shaikh Avatar asked Mar 26 '12 12:03

Yasser Shaikh


People also ask

Can a class library have an app config file?

Class libraries can access configuration settings in the same way as executable apps, however, the configuration settings must exist in the client app's App. config file.

How do I access config in C#?

New Project > Visual C# > Console Application Configuration assembly reference to access configuration settings, using ConfigurationManager. To add the reference, just right click References and click to add references. Now, we can see that System. Configuration reference has been added successfully to our project.


2 Answers

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

like image 78
Darren Avatar answered Sep 25 '22 06:09

Darren


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];          
    }
}
like image 25
Vijay Channe Avatar answered Sep 25 '22 06:09

Vijay Channe