SqlConnectionStringBuilder Class

Overview

The SqlConnectionStringBuilder class provides a simple way to create and manage the contents of connection strings used by SqlConnection. It offers strongly typed properties for each option that can appear in a connection string.

Constructors

SignatureDescription
SqlConnectionStringBuilder() Initializes a new instance of the SqlConnectionStringBuilder class.
SqlConnectionStringBuilder(string connectionString) Initializes a new instance and populates the builder with the supplied connection string.

Properties

PropertyTypeDefaultDescription
DataSourcestring""Specifies the name or network address of the instance of SQL Server to connect to.
InitialCatalogstring""The name of the database.
IntegratedSecurityboolfalseIndicates whether Windows Authentication is used.
UserIDstring""The SQL Server login ID.
Passwordstring""The password for the SQL Server login ID.
EncryptboolfalseSpecifies whether SQL Server uses SSL encryption for all data sent between the client and server.
TrustServerCertificateboolfalseWhen Encrypt is true, indicates whether the channel should be encrypted without validating the server certificate.
MultipleActiveResultSetsboolfalseEnables or disables MARS (Multiple Active Result Sets).
ConnectTimeoutint15Number of seconds to wait while trying to establish a connection before terminating the attempt and generating an error.

Methods

MethodSignatureDescription
Clearvoid Clear()Removes all key/value pairs from the collection.
Removebool Remove(string keyword)Removes the specified keyword from the collection.
ContainsKeybool ContainsKey(string keyword)Returns a value indicating whether the collection contains the specified keyword.
ToStringstring ToString()Returns the connection string built from the current settings.

Examples

Basic usage

using System.Data.SqlClient;

var builder = new SqlConnectionStringBuilder
{
    DataSource = @"SERVER\INSTANCE",
    InitialCatalog = "AdventureWorks",
    IntegratedSecurity = true,
    MultipleActiveResultSets = true,
    Encrypt = true,
    TrustServerCertificate = false
};

string connString = builder.ToString();
// connString now contains a fully‑qualified connection string.

Parsing an existing connection string

string existing = "Data Source=.;Initial Catalog=Northwind;User ID=sa;Password=secret;Encrypt=True";
var builder = new SqlConnectionStringBuilder(existing);

Console.WriteLine($"DataSource: {builder.DataSource}");
Console.WriteLine($"Encrypt: {builder.Encrypt}");
builder.IntegratedSecurity = false; // override security mode
Console.WriteLine(builder.ToString());

Remarks

When constructing a connection string, avoid including sensitive information such as passwords in source control. Use secure storage mechanisms like Azure Key Vault or Windows Credential Manager.

For more advanced scenarios, see SqlConnection and SqlConnectionStringBuilder Extensions.