C# 从连接字符串中获取用户名和密码的正确方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9975122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 11:27:08  来源:igfitidea点击:

Right way to get username and password from connection string?

c#mysql.net-2.0connection-string

提问by nawfal

I have a connection string like this:

我有一个像这样的连接字符串:

"SERVER=localhost;DATABASE=tree;UID=root;PASSWORD=branch;Min Pool Size = 0;Max Pool Size=200"

How do I get the various database parameters out of it? I can get database name and server like this:

如何从中获取各种数据库参数?我可以像这样获取数据库名称和服务器:

serverName = conObject.DataSource;
dbName = conObject.Database;

I need the username and password as well similarly. No property is set on the MySqlConnection object.

我同样需要用户名和密码。MySqlConnection 对象上没有设置任何属性。

At present I do it like this:

目前我是这样做的:

public static void GetDatabaseParameters(string connectionString, out string serverName, out string dbName, out string userName, out string password)
{
    Match m = Regex.Match(connectionString, "SERVER=(.*?);DATABASE=(.*?);UID=(.*?);PASSWORD=(.*?);.*");

    //serverName = m.Groups[1].Value;
    //dbName = m.Groups[2].Value;
    userName = m.Groups[3].Value;
    password = m.Groups[4].Value;
}

Is there an accepted practice here?

这里有公认的做法吗?

采纳答案by ionden

You could use the SqlConnectionStringBuilderClass

您可以使用SqlConnectionStringBuilder

string conString = "SERVER=localhost;DATABASE=tree;UID=root;PASSWORD=branch;Min Pool Size = 0;Max Pool Size=200";
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(conString);
string user = builder.UserID;
string pass = builder.Password;