Get user and password from ConnectionStringSettings

隐身守侯 提交于 2019-12-22 01:33:35

问题


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>

回答1:


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.




回答2:


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



回答3:


var builder = new SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings["MyConString"].ConnectionString)
var user = builder.UserID;
var password = builder.Password;



回答4:


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();



回答5:


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 .




回答6:


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 { }
    }
}



回答7:


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;



回答8:


 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.




回答9:


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;
    }



回答10:


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);
}



回答11:


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]);


来源:https://stackoverflow.com/questions/7900201/get-user-and-password-from-connectionstringsettings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!