From time to time, you may have to access (in some code) the individual values of a database connectionstring – and what to do if you only have the connectionstring available?
In my case, it happened in Azure, where we normally use the connectionstring for Function Apps, but when I needed to deploy a Logic App, I suddenly needed the individual values (for the Logic App’s associated ‘API Connection’)
Here it tells us that this C# class can do the parsing, but it only mentions “Initial Catalog” and “Data Source” – and what do we do, if our connectionstring uses “Server” and “Database”
It turns out (also in above description) that the class can also handle the synonyms – so if your connectionstring uses “Database”, you can get that value via “InitialCatalog”.
Short example code showing the synonyms – it can be tested here
public static void Main()
{
var cs = “Server=tcp:yada1.database.windows.net,1433;Database=yada2-dev;Persist Security Info=False;User ID=yada3-dev;Password=yada4;...................”;
System.Data.SqlClient.SqlConnectionStringBuilder sb = new System.Data.SqlClient.SqlConnectionStringBuilder(cs);
Console.WriteLine($”Server: {sb[“Server”]}”);
Console.WriteLine($”DataSource: {sb.DataSource}”);
Console.WriteLine($”Database: {sb[“Database”]}”);
Console.WriteLine($”Database: {sb.InitialCatalog}”);
Console.WriteLine($”User: {sb.UserID}”);
Console.WriteLine($”Password: {sb.Password}”);
}