• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 454
  • Last Modified:

asp.net 4 get values from connection string

i have a sql connection string being stored in the web.config.

how can i pull items like server name, user name, password... inside of c# asp.net code?
1 Solution
You might can get the connection string and then split it into an array like below:

using System.Configuration;

string s = ConfigurationManager.ConnectionStrings["aspnetdbConnectionString"].ConnectionString;
        string[] arr = s.Split(';');
        Dictionary<string, string> keypairs = new Dictionary<string, string>();
        foreach (string st in arr)
            string[] kp = st.Split('=');
            if (kp.Length > 1)
                keypairs.Add(kp[0], kp[1]);
       string servername = keypairs["Data Source"]; //access the items using the keys

Note: There should be an easy way but this was what I came up with

If you are working with SQL server you may find the SqlConnectionStringBuilder Class helpful.

The following is the msdn doco with example

Hope that helps

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now