Reputation: 17388
Having these items:
ConnDatabase
ConnServer
ConnUsername
ConnPassword
as strings, what is the best way to generate a SQL server connection string as can be found in a web.config file?
PS:
This is actually (most likely) intended for dapper
Upvotes: 1
Views: 565
Reputation: 46366
Assuming you're building a SQL connection string then there is a dedicated framework class for that: SqlConnectionStringBuilder
Here's a snippet from the MSDN article:
System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();
builder["Data Source"] = "(local)";
builder["integrated Security"] = true;
builder["Initial Catalog"] = "AdventureWorks;NewValue=Bad";
Console.WriteLine(builder.ConnectionString);
which results in this safely (quoted) value of:
Source=(local);Initial Catalog="AdventureWorks;NewValue=Bad";Integrated Security=True
This class also helps with parsing connection strings, which can be very useful (if not more useful than building them, IMO):
var builder = new SqlConnectionStringBuilder();
builder.ConnectionString = myConnectionString;
var dataSource = builder["Data Source"];
Upvotes: 4