Getting initial catalog from the web.config file

Chris picture Chris · Feb 24, 2011 · Viewed 11.3k times · Source

I have a connection string in the web.config file. I have to get the database name from it. Let say my connection sting is

<add name="LocalSqlServer" connectionString="Data Source=XYZ;Initial Catalog=MyDataBase;Integrated Security=true" providerName="System.Data.SqlClient"/>

I want to get the database name [i.e. Initial Catalog] from the connection string.

How can I get it?

Answer

marc_s picture marc_s · Feb 24, 2011

You can use the SqlConnectionStringBuilder for this purpose:

string connectionString = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;

SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString);

string database = builder.InitialCatalog;