Database Connection String Info

前端 未结 6 1221
误落风尘
误落风尘 2020-12-31 10:55

In .Net is there a class in .Net where you can get the DB name, and all the connection string info without acutally doing a substring on the connection string?

EDIT:

6条回答
  •  时光说笑
    2020-12-31 11:25

    You can use the provider-specific ConnectionStringBuilder class (within the appropriate namespace), or System.Data.Common.DbConnectionStringBuilder to abstract the connection string object if you need to. You'd need to know the provider-specific keywords used to designate the information you're looking for, but for a SQL Server example you could do either of these two things:

    Given

    string connectionString = "Data Source = .\\SQLEXPRESS;Database=Northwind;Integrated Security=True;";
    

    You could do...

    System.Data.Common.DbConnectionStringBuilder builder = new System.Data.Common.DbConnectionStringBuilder();
    
    builder.ConnectionString = connectionString;
    
    string server = builder["Data Source"] as string;
    string database = builder["Database"] as string;
    

    Or

    System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();
    
    builder.ConnectionString = connectionString;
    
    string server = builder.DataSource;
    string database = builder.InitialCatalog;
    

提交回复
热议问题