Convert string to ConnectionStringSettings

In my project, I have a method that should return a ConnectionStringSettings object. Since the database and server name will change dynamically, I need to dynamically build the connection string.

How to convert string to ConnectionStringSettings ?

 public ConnectionStringSettings getConnection(string server, string database) { //ConnectionStringSettings connsettings = new ConnectionStringSettings(); string connection = ConfigurationManager.ConnectionStrings["myConnString"].ToString(); connection = string.Format(connection, server, database); // Need to convert connection to ConnectionStringSettings // Return ConnectionStringSettings } 

- web.config

 <add name="myConnString" connectionString="server={0};Initial Catalog={1};uid=user1;pwd=blah; Connection Timeout = 1000"/> 
+4
source share
1 answer

The constructor of the ConnectionStringSettings class has an overload that takes two strings (first the name of the connection string, and the second the connection string itself).

 public ConnectionStringSettings getConnection(string server, string database) { string connection = ConfigurationManager.ConnectionStrings["myConnString"].ToString(); connection = string.Format(connection, server, database); return new ConnectionStringSettings("myConnString", connection); } 

There is a third overload , which takes an extra line for the provider name.

+1
source

Source: https://habr.com/ru/post/1482626/


All Articles