Search code examples
c#class-library

Add connectionstring in app.config


I have a class library in C# has has several classes and a app.config. I have put ConnectionString in app.config as follows:

<connectionStrings>
    <add name="TRN_DB"
         connectionString="Database=TRN;Server=NDTSSN;User ID=ln_users2;Password=%4nu$r!;Connection Timeout=30;pooling=false;" 
         providerName="System.Data.SqlClient"
    />
</connectionStrings>

I try to open connection string in one of the classes in my project as follows:

     string connectionString = ConfigurationManager.ConnectionStrings["TRN_DB"].ConnectionString.ToString();
       SqlConnection con = new SqlConnection(connectionString);
       con.Open();

But it gave me an error as:

{"Object reference not set to an instance of an object."}

The connection string is correct when I use same way in web project inside the web.config, Does anybody know how how I can access it in app.config? I already use it this way too:

 string connectionString = System.Configuration.ConfigurationSettings.AppSettings["TRN_DB"];

this one give me this error:

This method is obsolete, it has been replaced by System.Configuration!System.Configuration.ConfigurationManager.Appsettings

To make it clear, I don't have any other project in my solution, as I want my class library to work independently. I am not able to app web project and web.config to that. So I either should add connection string to app.config and access it Or add a web.config to my class library project. That I am not sure which one is doable.


Solution

  • If you are running Web project with Class library, add connection string to web.config inside the Web project

    If you are running Console/WinForm project with Class library, add connection string to app.config inside the Console/WinForm project

    modifying config in Library project will not work in your case.