28

I know this might be a very basic question, but maybe thats why I'm having problems finding the answer. Right now I'm creating database connections in my source files by doing something like this:

SqlConnection con = new SqlConnection("Data Source=...Password=...);
SqlCommand cmd = new SqlCommand(String.Format("SELECT * FROM Table;"), con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();

But this means that if I choose to change databases it will be a major pain. Do you guys know how to use the connection string from a web.config file instead?

Thank you!

David
  • 70,778
  • 16
  • 128
  • 169
Rob
  • 6,829
  • 14
  • 58
  • 90
  • 3
    Just out of curiosity, are you closing / disposing your connections / commands / readers? If you're not using the 'using' keyword, start! – RQDQ Mar 15 '11 at 19:39

6 Answers6

48
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringNameFromWebConfig"].ConnectionString);

Make sure that your website has a reference to System.Configuration or it won't work.

The documentation can be found as How to: Read Connection Strings from the Web.config File, with code sample

chridam
  • 95,056
  • 21
  • 214
  • 219
David
  • 70,778
  • 16
  • 128
  • 169
7

You can try

var conString = System.Configuration.
                ConfigurationManager.ConnectionStrings["connectionStringName"];
string strConnString = conString.ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
Bala R
  • 104,615
  • 23
  • 192
  • 207
  • 1
    +1: Note that the OP may have to manually add the System.Configuration reference to his project. – NotMe Mar 15 '11 at 19:36
5

In your app.config (or web.config):

<configuration>
       <connectionStrings>
           <add name="MainConnectString" connectionString="yourConnectionString" providerName="providerName" />
       </connectionStrings>
</configuration>

And in code:

string connectionString = ConfigurationManager.ConnectionStrings["MainConnectString"];
RQDQ
  • 14,902
  • 2
  • 28
  • 55
2

along with StackOverflowException's response, make sure to add using System.Configuration; to your code behind page

user279521
  • 4,749
  • 21
  • 74
  • 108
1

If you get "cannot implicitly convert type 'system.configuration.connectionstringsettings' to 'string'", do:

string connectionString = ConfigurationManager.ConnectionStrings["MainConnectString"].ConnectionString;
user1431356
  • 844
  • 7
  • 17
1

You can use EnterpriseLibrary.

using Microsoft.Practices.EnterpriseLibrary.Data;

Then you create a method to get connection string:

 public static string GetConnectionString()
    {
        Database YourData = DatabaseFactory.CreateDatabase("someconnectionname");
        return YourData .ConnectionString;
    }

In your web.config you will have following:

 <connectionStrings>   
   <add name="someconnectionname" connectionstring=..... />
 </connectionString>
OrahSoft
  • 763
  • 1
  • 5
  • 7