In my project I have a method which needs to return a ConnectionStringSettings
object. As the database and server name will change dynamically, I need to dynamically
construct the connection string.
How do I convert a 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"/>
The ConnectionStringSettings class constructor has an overload that takes two strings (first is the name of the connection string and the second is 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's a third overload that takes in an extra string for the name of the provider.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With