> This page location: /docs.md > /docs/drivers.md > /docs/languages/csharp.md > /docs/drivers/csharp/current.md

> For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

<!--
Tab options on this page. Append to the .md URL to filter:
  ?tabs=<id,...>   select specific tabs (e.g. ?tabs=nodejs,shell)
  ?allTabs=true    include every tab
  (no param)       default: one tab per tabset

Available tabs:
  other tabs: mongo-client-settings, mongo-url-builder
-->

# Specify Connection Options

## Overview

This page describes the connection options available in the .NET/C# Driver and explains how to apply them to your MongoDB connection.

## How to Specify Connection Options

The following sections describe the ways in which you can specify connection options.

### Using the Connection URI

If you pass a connection URI to the `MongoClient` constructor, you can include connection options in the string as `<name>=<value>` pairs. In the following example, the connection URI contains the `connectTimeoutMS` option with a value of `60000` and the `tls` option with a value of `true`:

```csharp
const string uri = "mongodb+srv:/localhost:27017/?connectTimeoutMS=60000&tls=true";
```

To learn more about the options that you can specify in a connection URI, see [Connection String Options](https://www.mongodb.com/docs/manual/reference/connection-string-options/) in the MongoDB Server manual.

### Using MongoClientSettings

You can use a `MongoClientSettings` object to configure connection settings in code rather than in a connection URI. Configuring the connection this way makes it easier to change settings at runtime, helps you catch errors during compilation, and provides more configuration options than the connection URI.

To set connection options in a `MongoClientSettings` object, perform the following steps:

1. Create an instance of the `MongoClientSettings` class

2. Set properties on the instance to configure the connection

3. Pass the instance to the `MongoClient` constructor

The following code example shows how to perform the preceding steps:

```csharp
var settings = new MongoClientSettings()
{
    Scheme = ConnectionStringScheme.MongoDBPlusSrv,
    Server = new MongoServerAddress("localhost", 27017),
    ConnectTimeout = TimeSpan.FromMilliseconds(60000),
    UseTls = true
};

var client = new MongoClient(settings);
```

You can also create a `MongoClientSettings` object from a connection string by calling the `MongoClientSettings.FromConnectionString()` method and passing the connection string, as shown in the following example. This is useful if you already have a connection string but want to modify some settings programmatically, or if you must specify settings that aren't available in the connection string.

```csharp
const string connectionUri = "mongodb+srv://localhost:27017/?connectTimeoutMS=60000&tls=true";
var settings = MongoClientSettings.FromConnectionString(connectionUri);
settings.ServerApi = new ServerApi(ServerApiVersion.V1);

var client = new MongoClient(settings);
```

Alternatively, you can create a `MongoClientSettings` object from a `MongoUrl` object by calling the `MongoClientSettings.FromUrl()` method and passing the `MongoUrl` object, as shown in the following example. This is useful if you already have a `MongoUrl` object but want to specify settings that aren't available in the `MongoUrl` class.

```csharp
const string connectionUri = "mongodb+srv://localhost:27017/?connectTimeoutMS=60000&tls=true";
var url = new MongoUrl(connectionUri);
var settings = MongoClientSettings.FromUrl(url);
settings.ServerApi = new ServerApi(ServerApiVersion.V1);

var client = new MongoClient(settings);
```

### Using MongoUrlBuilder

You can use a `MongoUrlBuilder` object to create and configure connection settings on a `MongoUrl` object. A `MongoUrl` is a strongly typed representation of a connection URI, and is useful when reading a connection URI directly from another source. Using a `MongoUrl` object has many of the same advantages as using a `MongoClientSettings` object, although the two classes contain different properties and methods.

To use a `MongoUrlBuilder` object, create an instance of the class and set the necessary configuration properties. To create a `MongoUrl` object from the `MongoUrlBuilder`, call the `MongoUrlBuilder.ToMongoUrl()` method. You can pass the `MongoUrl` object to the `MongoClient` constructor. The following code example shows this process:

```csharp
const string connectionUri = "mongodb+srv://localhost:27017/?connectTimeoutMS=60000&tls=true";
var builder = new MongoUrlBuilder(connectionUri)
{
    ServerMonitoringMode = MongoDB.Driver.Core.Servers.ServerMonitoringMode.Stream
};
var url = builder.ToMongoUrl();

var client = new MongoClient(url);
```

## Connection Options

The following sections describe the connection options available in the .NET/C# Driver and how to specify them by using a `MongoClientSettings` or `MongoUrlBuilder` object.

### Replica Set Options

### MongoClientSettings

#### DirectConnection

Specifies whether to force dispatch **all** operations to the host. If you specify this option, the driver doesn't accept the [DNS seed list connection format.](https://www.mongodb.com/docs/manual/reference/connection-string/#std-label-connections-dns-seedlist) You must use the [standard connection URI format](https://www.mongodb.com/docs/manual/reference/connection-string/#standard-connection-string-format/) instead. The default value is `false`.

This property must be set to `false` if you specify more than one host name.

```csharp
var settings = new MongoClientSettings
{
    DirectConnection = true,
};
```

#### ReplicaSetName

The name of the replica set to connect to. The default value is `null`.

```csharp
var settings = new MongoClientSettings
{
    ReplicaSetName = "yourReplicaSet",
};
```

### TLS Options

### MongoClientSettings

#### AllowInsecureTls

Specifies whether to relax TLS constraints as much as possible. This can include allowing invalid certificates or hostname mismatches. The default value is `false`.

If this property is set to `true` and `SslSettings.CheckCertificateRevocation` is set to `false`, the .NET/C# Driver will throw an exception.

The following code example shows how to set this option to `true`:

```csharp
var settings = new MongoClientSettings
{
    AllowInsecureTls = true,
};
```

#### SslSettings

TLS/SSL options, including client certificates, revocation handling, and enabled and disabled TLS/SSL protocols. The default value is `null`.

If `SslSettings.CheckCertificateRevocation` is set to `false` and `AllowInsecureTls` is set to `true`, the .NET/C# Driver throws an exception.

```csharp
var settings = new MongoClientSettings();
settings.SslSettings = new SslSettings()
{
    CheckCertificateRevocation = false,
    ClientCertificateSelectionCallback = new LocalCertificateSelectionCallback() { ... },
    ClientCertificates = new List<X509Certificate>() { ... },
    EnabledSslProtocols = SslProtocols.Tls13,
    ServerCertificateValidationCallback = new RemoteCertificateValidationCallback() { ... }
};
```

#### UseTls

Specifies whether to require TLS for connections to the server. If you use a scheme of `"mongodb+srv"` or specify other TLS options, this option defaults to `true`. Otherwise, it defaults to `false`.

```csharp
var settings = new MongoClientSettings
{
    UseTls = true,
};
```

### Timeout Options

### MongoClientSettings

#### ConnectTimeout

The length of time the driver tries to establish a single TCP socket connection to the server before timing out. The default value is 30 seconds.

```csharp
var settings = new MongoClientSettings
{
    ConnectTimeout = TimeSpan.FromSeconds(60),
};
```

#### SocketTimeout

The length of time the driver tries to send or receive on a socket before timing out. The default value is set by the operating system.

```csharp
var settings = new MongoClientSettings
{
    ConnectTimeout = TimeSpan.FromSeconds(60),
};
```

### Compression Options

### MongoClientSettings

#### Compressors

The preferred compression types, in order, for wire-protocol messages sent to or received from the server. The driver uses the first of these compression types that the server supports. The default value is `null`.

```csharp
var settings = new MongoClientSettings
{
    Compressors = new List<CompressorConfiguration>()
    {
        new(CompressorType.Zlib),
        new(CompressorType.Snappy)
    }
};
```

### Connection Pool Options

### MongoClientSettings

#### MaxConnecting

The greatest number of connections a driver's connection pool may be establishing concurrently. The default value is `2`.

```csharp
var settings = new MongoClientSettings
{
    MaxConnecting = 3,
};
```

#### MaxConnectionIdleTime

The length of time a connection can be idle before the driver closes it. The default value is 10 minutes.

```csharp
var settings = new MongoClientSettings
{
    MaxConnectionIdleTime = TimeSpan.FromMinutes(8),
};
```

#### MaxConnectionLifeTime

The length of time a connection can be pooled before expiring. The default value is 30 minutes.

```csharp
var settings = new MongoClientSettings
{
    MaxConnectionLifeTime = TimeSpan.FromMinutes(40),
};
```

#### MaxConnectionPoolSize

The greatest number of clients or connections the driver can create in its connection pool. This count includes connections in use. The default value is `100`.

```csharp
var settings = new MongoClientSettings
{
    MaxConnectionPoolSize = 150,
};
```

#### MinConnectionPoolSize

The number of connections the driver creates and keeps in the connection pool even when no operations are occurring. This count includes connections in use. The default value is `0`.

```csharp
var settings = new MongoClientSettings
{
    MinConnectionPoolSize = 3,
};
```

#### WaitQueueTimeout

The length of time the driver tries to check out a connection from a server's connection pool before timing out. The default value is two minutes.

```csharp
var settings = new MongoClientSettings
{
    WaitQueueTimeout = TimeSpan.FromSeconds(30),
};
```

### Write Concern Options

### MongoClientSettings

#### WriteConcern

The default write-concern settings, including write timeout and journaling, for the client. The default value is `WriteConcern.Acknowledged`. See [Write Concern](https://www.mongodb.com/docs/manual/reference/write-concern/) in the MongoDB Server manual for more information.

```csharp
var settings = new MongoClientSettings();
settings.WriteConcern = MongoDB.Driver.WriteConcern.Acknowledged;
settings.WriteConcern = new WriteConcern(
    w: 1,
    wTimeout: new TimeSpan(0, 0, 0, 30, 0),
    fsync: true,
    journal: true
);
```

### Read Concern Options

### MongoClientSettings

#### ReadConcern

The client's read concern. The default value is `ReadConcern.Default`. For more information, see [Read Concern](https://www.mongodb.com/docs/manual/reference/read-concern/) in the MongoDB Server manual.

```csharp
var settings = new MongoClientSettings
{
    ReadConcern = MongoDB.Driver.ReadConcern.Local,
};
```

### Read Preference Options

### MongoClientSettings

#### ReadPreference

The client's default read-preference settings. `MaxStaleness` represents the longest replication lag, in wall-clock time, that a secondary can experience and still be eligible for server selection. The default value is `ReadPreference.Primary`. Specifying `-1` means no maximum. See [Read Preference](https://www.mongodb.com/docs/manual/core/read-preference/) in the MongoDB Server manual for more information.

```csharp
var settings = new MongoClientSettings
{
    ReadPreference = MongoDB.Driver.ReadPreference.PrimaryPreferred,
};
```

### Authentication Options

### MongoClientSettings

#### Credential

Settings for how the driver authenticates to the server. This includes authentication credentials, mechanism, source, and other settings. The default value is `null`.

If you don't specify an authentication mechanism, the driver uses either `SCRAM-SHA-1` or `SCRAM-SHA-256`, depending on the server version. See [Authentication Mechanisms](https://www.mongodb.com/docs/drivers/csharp/current/security/authentication.md#std-label-csharp-authentication-mechanisms) for available authentication mechanisms.

```csharp
var settings = new MongoClientSettings
{
    Credential = MongoCredential.CreatePlainCredential(
        databaseName: "admin",
        username: "user",
        password: "password"
    )
};
```

### Server Selection and Discovery Options

### MongoClientSettings

#### HeartbeatInterval

The interval between regular server-monitoring checks. Must be greater than or equal to 500 milliseconds. The default value is `10000` milliseconds (10 seconds).

```csharp
var settings = new MongoClientSettings
{
    HeartbeatInterval = TimeSpan.FromSeconds(5)
};
```

#### HeartbeatTimeout

The length of time a monitoring socket can be idle before timing out. The default value is the value of the `ConnectTimeout` property.

```csharp
var settings = new MongoClientSettings
{
    HeartbeatTimeout = TimeSpan.FromSeconds(5)
};
```

#### LocalThreshold

The latency window for server eligibility. If a server's round trip takes longer than the fastest server's round-trip time plus this value, the server isn't eligible for selection. The default value is 15 milliseconds.

```csharp
var settings = new MongoClientSettings
{
    LocalThreshold = TimeSpan.FromSeconds(15)
};
```

#### ServerSelectionTimeout

The latency window for server eligibility. If a server's round trip takes longer than the fastest server's round-trip time plus this value, the server isn't eligible for selection. The default value is 15 milliseconds.

```csharp
var settings = new MongoClientSettings
{
    ServerSelectionTimeout = TimeSpan.FromSeconds(30)
};
```

### Encoding Options

#### ReadEncoding

The UTF-8 encoding to use for string deserialization. The default value is strict encoding, where the driver throws an exception when it encounters an invalid UTF-8 byte sequence

```csharp
var settings = new MongoClientSettings
{
    ReadEncoding = new UTF8Encoding(
        encoderShouldEmitUTF8Identifier: false,
        throwOnInvalidBytes: true)
};
```

#### WriteEncoding

The UTF-8 encoding to use for string serialization. The default value is strict encoding, where the driver throws an exception when it encounters an invalid UTF-8 byte sequence

```csharp
var settings = new MongoClientSettings
{
    WriteEncoding = new UTF8Encoding(
        encoderShouldEmitUTF8Identifier: false,
        throwOnInvalidBytes: true)
};
```

**Note: MongoClientSettings Only**

The `ReadEncoding` and `WriteEncoding` properties are available only in the `MongoClientSettings` class.

### Stable API

#### ServerApi

Allows opting into Stable API versioning. The default value is `null`. See [Stable API](https://www.mongodb.com/docs/manual/reference/stable-api/) in the MongoDB Server manual for more information about Stable API versioning.

```csharp
var settings = new MongoClientSettings
{
    ServerApi = new ServerApi(
        ServerApiVersion.V1,
        strict: true,
        deprecationErrors: true),
};
```

**Note: MongoClientSettings Only**

The `ServerApi` property is available only in the `MongoClientSettings` class.

### Retry Options

### MongoClientSettings

#### RetryReads

Enables retryable reads. The default value is `true`.

```csharp
var settings = new MongoClientSettings
{
    RetryReads = false,
};
```

#### RetryWrites

Enables retryable writes. The default value is `true`.

```csharp
var settings = new MongoClientSettings
{
    RetryWrites = false,
};
```

### Miscellaneous Options

### MongoClientSettings

#### ApplicationName

The app name the driver passes to the server in the client metadata as part of the connection handshake. The server prints this value to the MongoDB logs once the connection is established. The value is also recorded in the slow query logs and profile collections. The default value is `null`.

```csharp
var settings = new MongoClientSettings
{
    ApplicationName = "yourAppName",
};
```

#### AutoEncryptionOptions

Settings for automatic client-side encryption. The default value is `null`. To learn more about client-side encryption, see [In-Use Encryption.](https://www.mongodb.com/docs/drivers/csharp/current/security/in-use-encryption.md#std-label-csharp-in-use-encryption)

```csharp
var settings = new MongoClientSettings
{
    AutoEncryptionOptions = new AutoEncryptionOptions(
        keyVaultNamespace: new CollectionNamespace(
            databaseName: "keyvault",
            collectionName: "datakeys"),
        kmsProviders: new Dictionary<string, IReadOnlyDictionary<string, object>> ()
        {
            { "local", new Dictionary<string, object> () { { "key", "<base64-encoded-key>" } } }
        }
    ),
};
```

#### ClusterConfigurator

Low-level configuration options for sockets, TLS, cluster, and others. The default value is `null`.

```csharp
var settings = new MongoClientSettings
{
    ClusterConfigurator = builder =>
    {
        builder
            .Subscribe<ClusterOpenedEvent>(e =>
            {
                Console.WriteLine($"Cluster opened: Cluster ID = {e.ClusterId}");
            })
            .Subscribe<ClusterDescriptionChangedEvent>(e =>
            {
                Console.WriteLine($"Cluster description changed: {e.NewDescription}");
            });
    }
};
```

#### IPv6

Specifies whether the host address is in IPv6 format. The default value is `false`.

```csharp
var settings = new MongoClientSettings
{
    IPv6 = true,
};
```

#### IsFrozen

A read-only option that indicates whether the settings have been frozen. You can't change frozen settings. The default value is `false`.

```csharp
var settings = new MongoClientSettings();
if (!settings.IsFrozen)
{
    settings.RetryReads = false;
}
```

**Tip: Freeze Settings**

You can freeze the settings on a `MongoClientSettings` object by calling its [Freeze()](https://mongodb.github.io/mongo-csharp-driver/3.13.0/api/MongoDB.Driver/MongoDB.Driver.MongoClientSettings.Freeze.html) method. This prevents any further changes to the settings.

Alternatively, you can call the [FrozenCopy()](https://mongodb.github.io/mongo-csharp-driver/3.13.0/api/MongoDB.Driver/MongoDB.Driver.MongoClientSettings.FrozenCopy.html) method to create a new `MongoClientSettings` object with the current settings frozen.

#### LibraryInfo

The name and version of a custom library built on the .NET/C# Driver. The driver sends this information to the server.

```csharp
var settings = new MongoClientSettings
{
    LibraryInfo = new LibraryInfo("customLibraryName", "1.0.0")
};
```

#### LoadBalanced

Specifies whether the driver is connecting to a load balancer. You can set this property to `true` only if all the following conditions are met:

- You specify just one host name

- You're not connecting to a replica set

- You're not using the `SrvMaxHosts` property

- You're not using the `DirectConnection` property

The default value is `false`.

```csharp
var settings = new MongoClientSettings
{
    LoadBalanced = true,
};
```

#### LoggingSettings

The settings used for [logging.](https://www.mongodb.com/docs/drivers/csharp/current/logging-and-monitoring/logging.md#std-label-csharp-logging) The default value is `null`.

```csharp
var settings = new MongoClientSettings
{
    LoggingSettings = new LoggingSettings(
        LoggerFactory.Create(l =>
            l.SetMinimumLevel(LogLevel.Debug)))
};
```

#### Scheme

Specifies whether to use the standard connection string format (`MongoDB`) or the DNS seed list format (`MongoDBPlusSrv`). The available values for this property are defined in the [ConnectionStringScheme](https://mongodb.github.io/mongo-csharp-driver/3.13.0/api/MongoDB.Driver/MongoDB.Driver.Core.Configuration.ConnectionStringScheme.html) enum. The default value is `ConnectionStringScheme.MongoDB`. See [Connection Strings](https://www.mongodb.com/docs/manual/reference/connection-string/) in the MongoDB Server manual for more information about connection string formats.

If the `DirectConnection` property is set to `true` and you try to use the DNS seed list format, the .NET/C# Driver will throw an exception.

```csharp
var settings = new MongoClientSettings
{
    Scheme = ConnectionStringScheme.MongoDBPlusSrv,
};
```

#### Server

The host and port number where MongoDB is running. The default value is `localhost:27017`.

```csharp
var settings = new MongoClientSettings
{
    Server = new MongoServerAddress("localhost", 27017)
};
```

#### ServerMonitoringMode

Specifies the server monitoring protocol to use. The available values for this property are defined in the [ServerMonitoringMode](https://mongodb.github.io/mongo-csharp-driver/3.13.0/api/MongoDB.Driver/MongoDB.Driver.Core.Servers.ServerMonitoringMode.html) enum. The default value is `Auto`.

When this option is set to `Auto` the monitoring mode is determined by the environment in which the driver is running. The driver uses polling mode in function-as-a-service (FaaS) environments, such as AWS Lambda, and the streaming mode in other environments.

```csharp
var settings = new MongoClientSettings
{
    ServerMonitoringMode = MongoDB.Driver.Core.Servers.ServerMonitoringMode.Stream
};
```

#### Servers

The cluster members where MongoDB is running. The default value is `localhost:27017`.

```csharp
var settings = new MongoClientSettings
{
    Servers = new List<MongoServerAddress>()
    {
        new ("localhost", 27017),
        new ("localhost", 27018)
    }
};
```

#### SrvMaxHosts

The greatest number of SRV results to randomly select when initially populating the seedlist or, during SRV polling, adding new hosts to the topology. The default value is `0`.

You can use this property only if the connection-string scheme is set to `ConnectionStringScheme.MongoDBPlusSrv`. You cannot use it when connecting to a replica set.

```csharp
var settings = new MongoClientSettings
{
    SrvMaxHosts = 5
};
```

#### SrvServiceName

The service name of the [SRV resource records](https://www.rfc-editor.org/rfc/rfc2782) that the driver retrieves to construct your seedlist. The driver uses the service name to create the SRV URI, which matches the following format:

```text
_{srvServiceName}._tcp.{hostname}.{domainname}
```

This property overrides the default service name for SRV lookup in discovery and polling. The default value is `"mongodb"`.

You can use this property only if the connection-string scheme is set to `ConnectionStringScheme.MongoDBPlusSrv`. You cannot use it when connecting to a replica set.

```csharp
var settings = new MongoClientSettings
{
    SrvServiceName = "yourServiceName"
};
```

#### TranslationOptions

Specifies options, such as the MongoDB Server version, for translating LINQ queries to the Query API. The default value is `null`.

```csharp
var settings = new MongoClientSettings
{
    TranslationOptions = new ExpressionTranslationOptions()
    {
        CompatibilityLevel = ServerVersion.Server80,
        EnableClientSideProjections = true
    }
};
```

## Additional Information

For more information about the types used on this page, see the following API documentation:

- [MongoClientSettings](https://mongodb.github.io/mongo-csharp-driver/3.13.0/api/MongoDB.Driver/MongoDB.Driver.MongoClientSettings.html)

- [MongoUrl](https://mongodb.github.io/mongo-csharp-driver/3.13.0/api/MongoDB.Driver/MongoDB.Driver.MongoUrl.html)

- [MongoUrlBuilder](https://mongodb.github.io/mongo-csharp-driver/3.13.0/api/MongoDB.Driver/MongoDB.Driver.MongoUrlBuilder.html)

- [AutoEncryptionOptions](https://mongodb.github.io/mongo-csharp-driver/3.13.0/api/MongoDB.Driver/MongoDB.Driver.AutoEncryptionOptions.html)

- [ClusterDescriptionChangedEvent](https://mongodb.github.io/mongo-csharp-driver/3.13.0/api/MongoDB.Driver/MongoDB.Driver.Core.Events.ClusterDescriptionChangedEvent.html)

- [ClusterOpenedEvent](https://mongodb.github.io/mongo-csharp-driver/3.13.0/api/MongoDB.Driver/MongoDB.Driver.Core.Events.ClusterOpenedEvent.html)

- [CollectionNamespace](https://mongodb.github.io/mongo-csharp-driver/3.13.0/api/MongoDB.Driver/MongoDB.Driver.CollectionNamespace.html)

- [CompressorConfiguration](https://mongodb.github.io/mongo-csharp-driver/3.13.0/api/MongoDB.Driver/MongoDB.Driver.Core.Configuration.CompressorConfiguration.html)

- [CompressorType](https://mongodb.github.io/mongo-csharp-driver/3.13.0/api/MongoDB.Driver/MongoDB.Driver.Core.Compression.CompressorType.html)

- [ConnectionStringScheme](https://mongodb.github.io/mongo-csharp-driver/3.13.0/api/MongoDB.Driver/MongoDB.Driver.Core.Configuration.ConnectionStringScheme.html)

- [ExpressionTranslationOptions](https://mongodb.github.io/mongo-csharp-driver/3.13.0/api/MongoDB.Driver/MongoDB.Driver.ExpressionTranslationOptions.html)

- [LoggingSettings](https://mongodb.github.io/mongo-csharp-driver/3.13.0/api/MongoDB.Driver/MongoDB.Driver.Core.Configuration.LoggingSettings.html)

- [MongoCredential](https://mongodb.github.io/mongo-csharp-driver/3.13.0/api/MongoDB.Driver/MongoDB.Driver.MongoCredential.html)

- [MongoServerAddress](https://mongodb.github.io/mongo-csharp-driver/3.13.0/api/MongoDB.Driver/MongoDB.Driver.MongoServerAddress.html)

- [ReadConcern](https://mongodb.github.io/mongo-csharp-driver/3.13.0/api/MongoDB.Driver/MongoDB.Driver.ReadConcern.html)

- [ReadConcernLevel](https://mongodb.github.io/mongo-csharp-driver/3.13.0/api/MongoDB.Driver/MongoDB.Driver.ReadConcernLevel.html)

- [ReadPreference](https://mongodb.github.io/mongo-csharp-driver/3.13.0/api/MongoDB.Driver/MongoDB.Driver.ReadPreference.html)

- [ServerApi](https://mongodb.github.io/mongo-csharp-driver/3.13.0/api/MongoDB.Driver/MongoDB.Driver.ServerApi.html)

- [WriteConcern](https://mongodb.github.io/mongo-csharp-driver/3.13.0/api/MongoDB.Driver/MongoDB.Driver.WriteConcern.html)
