This C# code snippet parses the specified connection string to find the host name, instance name, and database name. It returns them in a GroupCollection .
using System.Text.RegularExpressions;
...
const string CONNECTION_STRING_PATTERN
= @"=(?.+);Initial Catalog=(?\w+);";
static readonly Regex ConnectionString_Regex
= new Regex (CONNECTION_STRING_PATTERN, RegexOptions.IgnoreCase);
static GroupCollection ParseConnectionString (string inputString)
{
Match match = ConnectionString_Regex.Match (inputString);
return match.Groups;
}
The following is an alternative method:
static void ParseConnectionString(string inputString)
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(inputString);
// retrieve Data source and Db name ; even user id and password using builder instance
// like builder.DataSource(Server name);builder.InitialCatalog(DB Name);
// builder.UserID(User Id);builder.Password(Password)
}