1

Here is my string line:

string conSTR = "Data Source=(local);Initial Catalog=MyDB;User ID=sa";

I just want to get the string "(local)", and "MyDb" and "sa" word anybody can suggest how to do it in C#.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
odlan yer
  • 721
  • 1
  • 7
  • 15
  • You should take a look at some regular expressions. Check this question: http://stackoverflow.com/questions/11717707/best-way-to-split-a-string-without-a-sperator/11717893#11717893 – Andre Calil Jul 30 '12 at 09:15
  • Best way is to use SqlConnectionStringBuilder class – Nikhil Agrawal Jul 30 '12 at 09:15
  • 1
    Do you want to parse connection strings, or you question is more generic one? – Sergei Rogovtcev Jul 30 '12 at 09:16
  • @Serg, I will not use this to just parse a connection string to connect to connect to sql db, I will also use this to connect my connection properties on connecting my crystal report like this crConnectionInfo.ServerName = "(local)"; crConnectionInfo.DatabaseName = "MyDB"; crConnectionInfo.UserID = "sa"; crConnectionInfo.Password = ""; – odlan yer Jul 30 '12 at 09:24
  • Use Skeet's answer than. – Sergei Rogovtcev Jul 30 '12 at 09:28

2 Answers2

10

Assuming this is actually a SQL connection string, you could use SqlConnectionStringBuilder - pass the string into the constructor, then interrogate the appropriate properties.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3

Use a SqlConnectionStringBuilder:

var builder = new SqlConnectionStringBuilder(conSTR);

Then you can read the builder's properties, like .DataSource, .UserID and .Password.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272