Hand-building a SQL Server connection string is error-prone and opens the door to injection through malformed values. SqlConnectionStringBuilder gives you strongly typed properties for every recognised key/value pair, validates input on assignment, and produces a correctly escaped connection string automatically.
If you have ever seen a connection string where a value contained a semicolon and quietly broke everything downstream, this class is the fix.
When connection string values are assembled by concatenating strings, an attacker or a misconfigured config file can inject extra key/value pairs simply by including a semicolon in a value. There is no built-in sanitisation when you build the string manually, so a value like AnayaDB;NewValue=Bad would silently append a second key to your connection string.
SqlConnectionStringBuilder validates every assignment against a fixed collection of known keys and their synonyms. Assigning an unsafe value does not throw an exception; instead, the builder quotes the value so it is treated as a literal string rather than parsed as an additional key/value pair.
System.Data.SqlClient.SqlConnectionStringBuilder builder =
new System.Data.SqlClient.SqlConnectionStringBuilder();
builder["Data Source"] = "(local)";
builder["integrated Security"] = true;
builder["Initial Catalog"] = "AnayaDB;NewValue=Bad";
Console.WriteLine(builder.ConnectionString);
The result is the following connection string, where the dangerous semicolon inside the catalog value is handled safely by quoting the entire value:
Data Source=(local);Initial Catalog="AnayaDB;NewValue=Bad";Integrated Security=True
The injected NewValue=Bad fragment is never parsed as a separate key because the builder wrapped the whole value in quotes. Any downstream SqlConnection that reads this string will connect to the database named AnayaDB;NewValue=Bad literally, which will simply fail to resolve rather than silently altering connection behaviour.
"integrated Security" (mixed case, space) is accepted and will be output as the canonical Integrated Security in the final connection string. The same applies to synonyms like Server vs Data Source and Database vs Initial Catalog.
Use SqlConnectionStringBuilder any time a connection string is assembled from parts that you do not fully control at compile time.
- Reading individual connection parameters from
appsettings.jsonor environment variables and combining them at runtime. - Allowing users or configuration UIs to supply a server name, database name, or credentials without the risk of injection.
- Writing tooling or admin utilities that construct connection strings programmatically across multiple target databases.
- Normalising connection strings read from external sources so that synonym keys and casing are made consistent before storage.