Question

I gave the above string,I want to get the serveripaddress,DB1,uid and **** these values from that string.

Was it helpful?

Solution

There is no need to parse a connection string when the BCL can do it for you:

var builder = new OleDbConnectionStringBuilder(connectionString);
var provider = builder.Provider;
var dataSource = builder.DataSource;
var initialCatalog = builder["Initial Catalog"];
var userID = builder["User ID"];
var password = builder["Password"];

Note that for an OLE DB connection string, only the standard cross-provider properties have strongly-typed property names, all the rest are accessed via the indexer.

OTHER TIPS

Don't use a regex.

Parse the connection string using SqlConnectionStringBuilder and then access the keys from that.

var b = new SqlConnectionStringBuilder(myConnectionString);
var dataSource = b["Data Source"]; 
// etc.

Much easier, more maintainable and more reliable.

data source=([^;]*);Initial Catalog=([^;]*);user id=([^;]*);Password=([^;"]*)

You then have the matches in groups 1 to 4. If you get bored you can name the groups; helps readability of the code, though rarely helps readability of the regex itself.

Isn't it easier to split value using ';' char and then split every item by '=' char?

This way your connection string could be edited by users and even item order could be changed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top