Right way to get username and password from connection string?

nawfal picture nawfal · Apr 2, 2012 · Viewed 40.1k times · Source

I have a connection string like this:

"SERVER=localhost;DATABASE=tree;UID=root;PASSWORD=branch;Min Pool Size = 0;Max Pool Size=200"

How do I get the various database parameters out of it? I can get database name and server like this:

serverName = conObject.DataSource;
dbName = conObject.Database;

I need the username and password as well similarly. No property is set on the MySqlConnection object.

At present I do it like this:

public static void GetDatabaseParameters(string connectionString, out string serverName, out string dbName, out string userName, out string password)
{
    Match m = Regex.Match(connectionString, "SERVER=(.*?);DATABASE=(.*?);UID=(.*?);PASSWORD=(.*?);.*");

    //serverName = m.Groups[1].Value;
    //dbName = m.Groups[2].Value;
    userName = m.Groups[3].Value;
    password = m.Groups[4].Value;
}

Is there an accepted practice here?

Answer

ionden picture ionden · Apr 2, 2012

You could use the SqlConnectionStringBuilder Class

string conString = "SERVER=localhost;DATABASE=tree;UID=root;PASSWORD=branch;Min Pool Size = 0;Max Pool Size=200";
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(conString);
string user = builder.UserID;
string pass = builder.Password;