Rash
Rash

Reputation: 447

How to get server name and database from config file

I have a connection string in my config file and i am using it in my code as follows -

SqlConnection sqlconn = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCentralW2"].ConnectionString);

I need to get the server name and the database from this and pass it as a parameter to my stored proc.

I am trying to get it as below but it is failing.

SqlConnection sqlconn = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCentralW2"].ConnectionString);
SqlConnectionStringBuilder conbuilder = new SqlConnectionStringBuilder();
conbuilder.ConnectionString = sqlconn.ToString();
string server = conbuilder.DataSource;
string database = conbuilder.InitialCatalog;

Please help me get the database and server name from my config file

Upvotes: 0

Views: 3928

Answers (3)

wandos
wandos

Reputation: 1619

i recommend that you store your connection string in your web.config than take it as it is, rather than build it

in web.config

<add name="connStr" connectionString="Data Source=.\SQLEXPRESS; Initial Catalog=dbtest; Integrated Security=SSPI" />

in the cs file

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

        con.Open();

Upvotes: 0

James
James

Reputation: 82136

Your not assigning the connection string property correctly, try:

builder.ConnectionString = ConfigurationManager.ConnectionStrings["DBCentralW2"].ConnectionString;

Or initialize your SqlConnectionStringBuilder class with the connection string e.g.

var conBuilder = new SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings["DBCentralW2"].ConnectionString);

Upvotes: 2

MMK
MMK

Reputation: 3721

Try Following:

 System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();    
        builder.ConnectionString = sqlconn.ConnectionString;
        string server = builder.DataSource;
        string database = builder.InitialCatalog;

Upvotes: 0

Related Questions