Search code examples
c#connection-stringstring-parsing

Parsing a Connection String


Is there a standard library or code snippet to get a value with a connection string like this?

string connstr = "DataServiceUrl=http://localhost/foo;" + 
        "RemoteServerConnection={server=http://localhost/foo2;interface=0.0.0.0;};" + 
        "publisherport=1234;StatisticsURL=http://localhost/foo3";

The whole inner connection property is kind of throwing this in a loop. I'd like to get specific values based on a key.

Here was the answer posted by John I used:

System.Data.Odbc.OdbcConnectionStringBuilder builder = new System.Data.Odbc.OdbcConnectionStringBuilder(); 
builder.ConnectionString = this.ConnectionString;
MessageBox.Show(builder["RemoteServerConnection"]);

Solution

  • Replacing "{" and "}" by (") does the trick:

    string conn = "DataServiceUrl=http://localhost/foo;" +
        "RemoteServerConnection={server=http://localhost/foo2;interface=0.0.0.0;};" +
        "publisherport=1234;StatisticsURL=http://localhost/foo3";
    
    var builder = new System.Data.Common.DbConnectionStringBuilder();
    builder.ConnectionString = conn.Replace("{", "\"").Replace("}", "\"");
    var keys = builder.Keys;
    var values = builder.Values;
    string remoteServerConnection = (string)builder["RemoteServerConnection"];