3

how do I get the connection string from app.config in another "class library project"

in the same class library I can use this code :

 DAL.Properties.Settings.Default.BayrueConnectionString;

but the issue is that I cannot get it from my web app.

thanks enter image description here

3
  • 2
    Class Libraries use the configuration file of the application that is using them, so the settings need to be in the application's configuration file, not the libraries. Libraries don't use config files. Commented Jun 25, 2013 at 7:37
  • as you can see I am using app.config Commented Jun 25, 2013 at 7:37
  • possible duplicate of .Net app.config in library project Commented Jun 25, 2013 at 7:38

3 Answers 3

4

I think there is no more elegant way than this. Add a static helper method to your class library which returns it.

public sealed class Helper
{
    private Helper()
    {
    }

    public static string GetBayrueConnectionString()
    {
        return DAL.Properties.Settings.Default.BayrueConnectionString;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I thinks this one will fix it.
0

Add reference to System.Configuration.

Use System.Configuration.ConfigurationManager.ConnectionStrings["DAL.Properties.Settings.BayrueConnectionString"]

4 Comments

Object reference not set to an instance of an object. this the error I am getting when use your code
Are you sure that the app.config file is located in the folder where you run your app?
the app.config is in another project
When you deploy your app all the files need to be in the same folder.
0

First, create a new ConnectionStrings.config file in the project you'd like to reference.

ConnectionStrings.config:

<connectionStrings>
    <add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data                        Source=(LocalDb)\v11.0;Initial Catalog=aspnet-MvcApplication-20130625013234;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-MvcApplication-20130625013234.mdf" />
</connectionStrings>

Next, unload your DAL project. Once unloaded, right click > Edit DAL.csproj.

Add the following element to the .csproj with the Include="{the ConnectionStrings.config you'd like to reference}":

<ItemGroup>
    <Content Include="..\ConnectionStrings.config" />
</ItemGroup>

Solution Explorer

Reload your project. This should add a ConnectionStrings.config file, shown above, to your project. Notice that both will open the same file. Now edit the app.config to reference the newly created .config file that was just added to your DAL:

<connectionStrings configSource="ConnectionStrings.config" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.