Get Database name from Connectionstring

March 5, 2015

I have requirement to extract database name property from connection string.
Here is the code to get it,

string connStr = "Data Source=SERVERx;Initial Catalog=DBx;User ID=u;Password=p"; 

var csb = new SqlConnectionStringBuilder(connStr);

string dataSource = csb.DataSource;
string initialCatalog = csb.InitialCatalog; //Here you get database name