How to pass ConnectionString parameters with variables?

Viewed 232

I have a ConnectionString and I want to pass it values (DataSource, Database, User ID, Password) with values from a .txt file and I need to read them, then pass them to the connectionString but I'm very confused how should I do this.

In my program I have a Helper Class to return the connectionString

public static class Helper
{
    public static string ConnectionString(string name)
    {
        return ConfigurationManager.ConnectionStrings[name].ConnectionString;
    }
}

This is how I call the connectionString so I can access the database data

using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(Helper.ConnectionString("Hotel")))
{
     connection.Execute($"INSERT INTO dbo.Registos_Cancelados(Nome, Telemovel, Data) VALUES(@Nome, @Telemovel, @Data)", new { Nome = nome, Telemovel = telemovel, Data = data });
}

I have a text file with the values

"DataSourceName"
"DataBaseName"
"User IDName"
"PasswordName"

And I want them in the connection string.

<connectionStrings>
    <add name="Hotel" connectionString="DataSource="DataSourceName";Database="DatabaseName";User Id="UserIdName";Password="PasswordName""
        providerName="System.Data.SqlClient" />
</connectionStrings>
2 Answers

You're using SqlClient, so: your best bet here is SqlConnectionStringBuilder:

var cb = new SqlConnectionStringBuilder(theBaseString);
cb.DataSource = dataSourceName;
cb.InitialCatalog = dataBaseName;
cb.UserID = userId;
cb.Password = password;
var connectionString = cb.ConnectionString;

If you don't have a template string (theBaseString), just use new SqlConnectionStringBuilder() instead.

The advantage of using SqlConnectionStringBuilder here is that it knows all about the escaping rules for non-trivial values, reserved characters, etc.

You can format your connection string like below to pass the necessary values like dbname later.

<connectionStrings>
    <add name="Hotel" connectionString="DataSource={0};Database={1};User Id={2};Password={3}"
        providerName="System.Data.SqlClient" />
</connectionStrings>

After that in your Helper class, return the formatted connection string with the values that you read from txt file.

public static string ConnectionString(string name)
    {
        var dataSourceName = "...";
        var dbName = "...";
        var userId = "...";
        var password = "...";

        var connectionString = ConfigurationManager.ConnectionStrings[name].ConnectionString;
        return string.Format(connectionString, dataSourceName, dbName, userId, password);
    }
Related