有的时候需要获取SQL Server数据库连接字符串的某些部分。用正则表达式可能有点麻烦。
其实有一个比较简单的方法--使用SqlConnectionStringBuilder。
var builder = new SqlConnectionStringBuilder(connectionString); var dbServer = builder.DataSource; var dbName = builder.InitialCatalog;
SqlConnectionStringBuilder还可以用来创建连接字符串。
var builder = new SqlConnectionStringBuilder(); builder["Data Source"] = "localhost"; builder.Add("Initial Catalog", "Demo"); builder.UserID = "sa"; builder.Password = "test"; builder.ApplicationName = "MyApp"; var connectionString = builder.ConnectionString;
本文如有不妥之处,请见谅。