23
votes

How can I get the user and password from such a connectionString in the app.config with a .NET function?

Of course I could read that string and get the value after the ID= and Password=.

<connectionStrings>
<add name="MyConString" connectionString="Data Source=(local);Initial Catalog=MyDatabase;Persist Security Info=True;User ID=MyUsername Password=MyPassword;Connect  providerName="System.Data.SqlClient"/>    
</connectionStrings>
11
I hope you noticed that you are missing a ';" after "MyUsername" - before "Password"John Gathogo

11 Answers

36
votes

use the ConnectionBuilderClass

SqlConnectionStringBuilder builder =  new SqlConnectionStringBuilder("Your connection string");
string password = builder.Password;


together with the

string connString = ConfigurationManager.ConnectionStrings["MyConString"].ConnectionString;

to achieve this.

4
votes
SqlConnectionStringBuilder con = new SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
string myUser = con.UserID;
string myPass = con.Password;
4
votes

If you need a more generic approach for parsing the connection string (one that doesn't deal with the specifics of one database provider) you can also use

System.Data.Common.DbConnectionStringBuilder

which is a base class for other classes like SqlConnectionStringBuilder etc.

You can create an instance of DbConnectionStringBuilder and in my case I needed to have one configurable connection string that I could get information from -- regardless of the database provider type. A few options if you need this flexibility -- you could create the appropriate ConnectionStringBuilder for your provider as others have suggested -- this would likely be required for most cases where provider-specific properties are needed.

Or if you want to read just a couple generic properties, you could use DbConnectionStringBuilder if you just need the user id and password for example.

This sample should work for ANY connection string that includes user id and password.

DbConnectionStringBuilder db = new DbConnectionStringBuilder();
db.ConnectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;

var username = db["User Id"].ToString();
var password = db["Password"].ToString();
2
votes
var builder = new SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings["MyConString"].ConnectionString)
var user = builder.UserID;
var password = builder.Password;
1
votes

You can get the connection string from the following

  SqlConnectionStringBuilder yourconn = new SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
string password = yourconn.Password;

You can then get the substring you are looking for .

0
votes

Just to add a bit to Tomas Walek's answer.

This approach would work only if "User ID" in the connection string is capitalized correctly. Oracle provider accepted "User Id" OK, but SqlConnectionStringBuilder did not work.

 public static class DbConnectionFactory
{
    public static ConnectionStringSettings AppConnectionSettings = ConfigurationManager.ConnectionStrings["{A connection string name}"];
    public static SqlConnectionStringBuilder AppConnBuilder = new SqlConnectionStringBuilder(AppConnectionSettings.ConnectionString);

    public static string DbUserID
    {
        get
        {
            return AppConnBuilder.UserID;
        }
        set { }
    }
}
0
votes

add a reference to System.Configuration and then use: using System.Configuration;

string MyDBConnection = ConfigurationManager.ConnectionStrings["MyDBConnection"].ConnectionString;
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(MyDBConnection);
string UserID = builder.UserID;
string Password = builder.Password;
string ServerName = builder.DataSource;
string DatabaseName = builder.InitialCatalog;
0
votes
 public static string GetConnectionSettings(string searchSetting ) 
 { 
     var con = ConfigurationManager.ConnectionStrings["yourConnectionHere"]‌​.ConnectionString; 
     String[] myString = con.Split(';'); 
     Dictionary<string, string> dict = new Dictionary<string, string>(); 

     for (int i = 0; i < myString.Count(); i++) 
     { 
         String[] con3 = myString[i].Split('='); dict.Add(con3[0], con3[1]); 
     } 

    return dict[searchSetting]; 
}

for searchSetting you can use what you want "User Is" or password.

0
votes

another way is to use regular expression (which I did), with a more forgiving pattern, to handle different ways a user id could be provided on the connection string:

    public static string GetUserIdFromConnectionString(string connectionString)
    {
        return new Regex("USER\\s+ID\\=\\s*?(?<UserId>\\w+)",
                RegexOptions.IgnoreCase)
            .Match(connectionString)
            .Groups["UserId"]
            ?.Value;
    }
-2
votes
var connString = ConfigurationManager.ConnectionStrings["MyConString"].ConnectionString;
var tokens = connString.Split(';');

string userId;
string password;

for(var i = 0;  i < tokens.Length; i++) {
    var token = tokens[i];
    if(token.StartsWith("User ID"))
        userId = token.Substring(token.IndexOf("=") + 1);

    if(token.StartsWith("Password"))
        password = token.Substring(token.IndexOf("=") + 1);
}
-2
votes
string connectionString = ConfigurationManager.ConnectionStrings["MyConString"].ConnectionString;
var tokens = connectionString.Split(';').Select(n => n.Split('=');
string userId = tokens.First(n => n[0].Equals("User ID").Select(n => n[1]);
string password = tokens.First(n => n[0].Equals("Password").Select(n => n[1]);