Is there any connection string parser in C#?

C#.Net

C# Problem Overview


I have a connection string and I want to be able to peek out for example "Data Source". Is there a parser, or do I have to search the string?

C# Solutions


Solution 1 - C#

Yes, there's the System.Data.Common.DbConnectionStringBuilder class.

> The DbConnectionStringBuilder class > provides the base class from which the > strongly typed connection string > builders (SqlConnectionStringBuilder, > OleDbConnectionStringBuilder, and so > on) derive. The connection string > builders let developers > programmatically create syntactically > correct connection strings, and parse > and rebuild existing connection > strings.

The subclasses of interest are:

System.Data.EntityClient.EntityConnectionStringBuilder
System.Data.Odbc.OdbcConnectionStringBuilder
System.Data.OleDb.OleDbConnectionStringBuilder
System.Data.OracleClient.OracleConnectionStringBuilder
System.Data.SqlClient.SqlConnectionStringBuilder

For example, to "peek out the Data Source" from a SQL-server connection string, you can do:

var builder = new SqlConnectionStringBuilder(connectionString);
var dataSource = builder.DataSource;

Solution 2 - C#

There are vendor specific connection string builders from various providers like SqlConnectionStringBuilder, MySqlConnectionStringBuilder, SQLiteConnectionStringBuilder etc (unfortunately there is no public interface from MS this time). Otherwise you have DbProviderFactory.CreateConnectionStringBuilder which will give you an alternate way to write it provider-agnostic way. You would need to specify provider in config file and have the right version of dll available. For eg.,

var c = "server=localhost;User Id=root;database=ppp";
var f = DbProviderFactories.GetFactory("MySql.Data.MySqlClient"); //your provider
var b = f.CreateConnectionStringBuilder();
b.ConnectionString = c;
var s = b["data source"];
var d = b["database"];

I had once written manual parsing for myself which did not give me any trouble. It would be trivial to extend this to give info on other parameters (right now its only for simple things like db name, data source, username and password). Like this or so:

static readonly string[] serverAliases = { "server", "host", "data source", "datasource", "address", 
                                           "addr", "network address" };
static readonly string[] databaseAliases = { "database", "initial catalog" };
static readonly string[] usernameAliases = { "user id", "uid", "username", "user name", "user" };
static readonly string[] passwordAliases = { "password", "pwd" };

public static string GetPassword(string connectionString)
{
    return GetValue(connectionString, passwordAliases);
}

public static string GetUsername(string connectionString)
{
    return GetValue(connectionString, usernameAliases);
}

public static string GetDatabaseName(string connectionString)
{
    return GetValue(connectionString, databaseAliases);
}

public static string GetServerName(string connectionString)
{
    return GetValue(connectionString, serverAliases);
}

static string GetValue(string connectionString, params string[] keyAliases)
{
    var keyValuePairs = connectionString.Split(';')
                                        .Where(kvp => kvp.Contains('='))
                                        .Select(kvp => kvp.Split(new char[] { '=' }, 2))
                                        .ToDictionary(kvp => kvp[0].Trim(),
                                                      kvp => kvp[1].Trim(),
                                                      StringComparer.InvariantCultureIgnoreCase);
    foreach (var alias in keyAliases)
    {
        string value;
        if (keyValuePairs.TryGetValue(alias, out value))
            return value;
    }
    return string.Empty;
}

For this you don't need anything special in config file, or any dll at all. Contains in Where clause is important only if you need to bypass poorly formatted connectionstrings like server = localhost;pp; where pp adds to nothing. To behave like normal builders (which would explode in these cases) change the Where to

.Where(kvp => !string.IsNullOrWhitespace(kvp))

Solution 3 - C#

Here's a couple lines of code that would parse any connection string into a dictionary:

Dictionary<string, string> connStringParts = connString.Split(';')
    .Select(t => t.Split(new char[] { '=' }, 2))
    .ToDictionary(t => t[0].Trim(), t => t[1].Trim(), StringComparer.InvariantCultureIgnoreCase);

And then you can access any part:

string dataSource = connStringParts["Data Source"];

Solution 4 - C#

I didn't really like all the answers here. So here is what I found.

With .NET Core

You can use built-in DbConnectionStringBuilder directly:

var builder = new System.Data.Common.DbConnectionStringBuilder();
builder.ConnectionString = "server=localhost;login=sa;pass=awesomeness";

var server = builder["server"];
var login = builder["login"];
var pass = builder["pass"];

Solution 5 - C#

You want to use DbProviderFactory.CreateConnectionStringBuilder () which provides you a connection string builder/parser specific to your connector, but does not require you to use any connector specific classes.

Solution 6 - C#

Use the SqlConnectionStringBuilder Unfortunately you will have to use a DB specific ConnectionStringBuilder as the connection strings differ.

Solution 7 - C#

Yes , You can do this using ConnectionStringBuilder Classes. Here is the list of available DbConnectionStringBuilder implementations for standard data providers:

System.Data.Odbc.OdbcConnectionStringBuilder
System.Data.OleDb.OleDbConnectionStringBuilder
System.Data.OracleClient.OracleConnectionStringBuilder
System.Data.SqlClient.SqlConnectionStringBuilder

here are sample example of parse connection string and display it's elements.

 string conString = @"Data Source=.\sqlexpress;" +
                        "Database=Northwind;Integrated Security=SSPI;" +
                        "Min Pool Size=5;Max Pool Size=15;Connection Reset=True;" +
                        "Connection Lifetime=600;";
    // Parse the SQL Server connection string and display it's properties
    
    SqlConnectionStringBuilder objSB1 = new SqlConnectionStringBuilder(conString);
    Response.Write("<b>Parsed SQL Connection String Parameters:</b>");
    Response.Write(" <br/>  Database Source = " + objSB1.DataSource);
    Response.Write(" <br/>  Database = " + objSB1.InitialCatalog);
    Response.Write(" <br/>  Use Integrated Security = " + objSB1.IntegratedSecurity);
    Response.Write(" <br/>  Min Pool Size = " + objSB1.MinPoolSize);
    Response.Write(" <br/>  Max Pool Size = " + objSB1.MaxPoolSize);
    Response.Write(" <br/>  Lifetime = " + objSB1.LoadBalanceTimeout);

Solution 8 - C#

You can use DbConnectionStringBuilder, and you don't need any specific provider:

The following code:

var cnstr = "Data Source=data source value;Server=ServerValue";
var builder = new DbConnectionStringBuilder();
builder.ConnectionString = cnstr;
Console.WriteLine("Data Source: {0}", builder["Data Source"]);
Console.WriteLine("Server: {0}", builder["Server"]);

Outputs to console:

Data Source: data source value
Server: ServerValue

EDIT:

Since DbConnectionStringBuilder implements IDictionary you can enumerate the connection string parameters:

foreach (KeyValuePair<string, object> kv in builder)
{
    Console.WriteLine("{0}: {1}", kv.Key, kv.Value);
}

Solution 9 - C#

So I found all of the existing answers were more or less wrong. I ended up with the following trivial solution:

class ConnectionStringParser: DbConnectionStringBuilder {
    ConnectionStringParser(string c) { Connection = c; }
    public override bool ShouldSerialize(string keyword) => true;
}

The parser is in DbConnectionStringBuilder and pretty much easy to get at. The only silly thing we have to do is set ShouldSerialize to always return true to prevent losing components when trying to round trip arbitrary connection strings.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAmir RezaeiView Question on Stackoverflow
Solution 1 - C#AniView Answer on Stackoverflow
Solution 2 - C#nawfalView Answer on Stackoverflow
Solution 3 - C#codeprose-samView Answer on Stackoverflow
Solution 4 - C#AndreiView Answer on Stackoverflow
Solution 5 - C#David ThielenView Answer on Stackoverflow
Solution 6 - C#EmondView Answer on Stackoverflow
Solution 7 - C#Jayesh SorathiaView Answer on Stackoverflow
Solution 8 - C#Jesús LópezView Answer on Stackoverflow
Solution 9 - C#JoshuaView Answer on Stackoverflow