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?
11 Answers
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;
-
11The base class
DbConnectionStringBuilder
has generic processing features that can be used without using subclasses:if (builder.TryGetValue("Password", out var pwd)) { string decrypted = SomehowDecrypt(pwd); builder["Password"] = decrypted; }
Jul 11, 2018 at 13:39
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))
-
@Icarus not really since the dictionary's key comparer is
StringComparer.InvariantCultureIgnoreCase
. See theToDictionary
overload– nawfalMar 21, 2013 at 20:03 -
1Yep, you are right, I just wrote a quick test. Will delete my original comment since it's wrong.– IcarusMar 21, 2013 at 20:51
-
4Your GetValue() method will not work in cases where for example the user has a
';'
or an'='
in their password. I had written a similar implementation and learned that it doesn't work the hard way. Gosh, connection string parsing is actually a lot harder than I thought! Dec 10, 2015 at 14:59 -
@Joshua I hope you're talking about the manual parsing part. Please take answers here as a starting point that could be worked on rather than foolproof and battle-tested solutions. I hope they are more valuable than comments that leave no information. You're also free to downvote. As far as I know, what needs to be further done is adhere to parsing standards. MS has one on msdn and it's been long in my mind to ammend. If only we all had time. '@'all please bear in mind the edge cases, esp one in Philip Atz's comment.– nawfalDec 19, 2017 at 3:49
-
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"];
-
3Smart, the only thing I would change would be include
StringSplitOptions.RemoveEmptyEntries
to the first split as it will cause aIndexOutOfRange
exception if there is a trailing;
Jul 1, 2013 at 19:24 -
2This works, but the connection string builders are more robust. Code like this will throw low-level exceptions instead of more meaningful parsing errors in the case of invalid connection strings.– SamSep 26, 2013 at 5:06
-
This helped me parse an ADO connection string so I could build an equivalent
SqlConnection
with theSqlConnectionStringBuilder
. Apr 9, 2015 at 20:37 -
Some caveats here. Connection string values can be enclosed in quotes, for example. Jul 9, 2018 at 17:32
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"];
-
One-liner version:
var server = new DbConnectionStringBuilder { ConnectionString = settings.ConnectionString }["server"]
Nov 3, 2021 at 12:15
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.
Use the SqlConnectionStringBuilder Unfortunately you will have to use a DB specific ConnectionStringBuilder as the connection strings differ.
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);
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);
}
-
This assumes you already know that the connection string has a "Data Source" value, etc., which isn't always true, as noted in stackoverflow.com/a/15529085/534109, above. Feb 9, 2015 at 21:19
-
My answer addrees specifically what the op ask: 'I want to be able to peek out for example "Data Source"' Feb 10, 2015 at 6:21
-
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.
-
4What was wrong with existing answers? Or what does your solution fix. Explanation would be helpful.– nawfalDec 19, 2017 at 4:03
In general I use my own construct, as it's simple easy and don't have additional dependency
private Dictionary<string, string> ParseConnectionString(string stringData, char propDelim = ';', char kvDelim = '=')
{
Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
Array.ForEach<string>(stringData.Split(propDelim), s =>
{
if (s != null && s.Length != 0)
keyValuePairs.Add(s.Split(kvDelim)[0], s.Split(kvDelim)[1]);
});
return keyValuePairs;
}
I wrote a dotnet code lib Sekvap (nuget: SrkSekvap) to parse this kind of string. It is not limited to connection strings as the general format can be used for many other usages.
The main difference is the ability to have a "main value" in front of the string; but it will parse connection strings as-is.
Also, the lib is very small and without dependencies. That may be an alternative to the other answers.