Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass ConnectionString parameters with variables?

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>
like image 389
romanCastro Avatar asked Sep 14 '25 09:09

romanCastro


1 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.

like image 111
Marc Gravell Avatar answered Sep 17 '25 00:09

Marc Gravell