Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert string to ConnectionStringSettings

Tags:

c#

.net

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"/>
like image 694
Henry Avatar asked Oct 22 '22 09:10

Henry


1 Answers

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.

like image 162
keyboardP Avatar answered Oct 30 '22 14:10

keyboardP