简体   繁体   English

从ConnectionStringSettings获取用户名和密码

[英]Get user and password from ConnectionStringSettings

How can I get the user and password from such a connectionString in the app.config with a .NET function? 如何使用.NET函数从app.config中的这样一个connectionString获取用户和密码?

Of course I could read that string and get the value after the ID= and Password=. 当然我可以读取该字符串并获取ID =和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>

use the ConnectionBuilderClass 使用ConnectionBuilderClass

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


together with the 与...一起

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

to achieve this. 为达到这个。

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

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 System.Data.Common.DbConnectionStringBuilder

which is a base class for other classes like SqlConnectionStringBuilder etc. 这是其他类的基类,如SqlConnectionStringBuilder等。

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. 您可以创建DbConnectionStringBuilder的实例,在我的情况下,我需要有一个可配置的连接字符串,我可以从中获取信息 - 无论数据库提供程序类型如何。 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. 如果您需要这种灵活性,可以选择一些选项 - 您可以像其他人所建议的那样为您的提供商创建适当的ConnectionStringBuilder--对于需要提供者特定属性的大多数情况,这可能是必需的。

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. 或者,如果您只想阅读几个通用属性,则可以使用DbConnectionStringBuilder,例如,如果您只需要用户ID和密码。

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();
var builder = new SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings["MyConString"].ConnectionString)
var user = builder.UserID;
var password = builder.Password;

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 . 然后,您可以获取要查找的子字符串。

Just to add a bit to Tomas Walek's answer. 只是为Tomas Walek的回答添加一点。

This approach would work only if "User ID" in the connection string is capitalized correctly. 仅当连接字符串中的“用户ID”正确大写时,此方法才有效。 Oracle provider accepted "User Id" OK, but SqlConnectionStringBuilder did not work. Oracle提供程序接受“用户ID”确定,但SqlConnectionStringBuilder不起作用。

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

add a reference to System.Configuration and then use: using System.Configuration; 添加对System.Configuration的引用,然后使用: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;
 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. 对于searchSetting,您可以使用您想要的“用户是”或密码。

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: 另一种方法是使用正则表达式(我做了),使用更宽容的模式,来处理在连接字符串上提供用户ID的不同方式:

    public static string GetUserIdFromConnectionString(string connectionString)
    {
        return new Regex("USER\\s+ID\\=\\s*?(?<UserId>\\w+)",
                RegexOptions.IgnoreCase)
            .Match(connectionString)
            .Groups["UserId"]
            ?.Value;
    }
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);
}
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]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM