使用Regex从连接字符串中提取属性

时间:2017-11-15 15:31:36

标签: c# regex

C#我试图从连接字符串中获取Data Sourceinitial catalog属性。

所以,如果我有

metadata=res://*/model.csdl|res://*/model.ssdl|res://*/model.msl;provider=System.Data.SqlClient;provider connection string="data source=myDESKTOP;initial catalog=dbName;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"

如果表达式左侧的情况如何,我如何仅提取值myDESKTOPdbName

1 个答案:

答案 0 :(得分:2)

您可以剖析Entity Framework的连接字符串并提取内部基本连接字符串。此时,SqlConnectionStringBuilder可以为您提供组成连接字符串的各个部分

string test = "metadata=res://*/model.csdl|res://*/model.ssdl|res://*/model.msl;provider=System.Data.SqlClient;provider connection string=\"data source = myDESKTOP; initial catalog = dbName; integrated security = True; MultipleActiveResultSets = True; App = EntityFramework";

string con = string.Join("=", 
                    string.Join(";", test.Split(';').Skip(2))
                          .Split('=').Skip(1)).Trim('"');

SqlConnectionStringBuilder sb = new SqlConnectionStringBuilder(con);
Console.WriteLine(sb.DataSource);
Console.WriteLine(sb.InitialCatalog);