Parse Endpoint Uri from CosmosDB connection string

Viewed 536

I have an environment variable containing a CosmosDB connection string, i.e. this format:

AccountEndpoint=https://ACCOUNTNAME.documents.azure.com:443/;AccountKey=STUFF==;

Before I connect to the native API (using CreateAndInitializeAsync, I want to log the endpoint Uri, but can't find a parsing API.

What's the best approach, ideally with minimal code?

2 Answers

You could use DbConnectionStringBuilder (docs):

using System.Data.Common;

string connectionString = "AccountEndpoint=https://ACCOUNTNAME.documents.azure.com:443/;AccountKey=STUFF==;";
var builder = new DbConnectionStringBuilder
{
    ConnectionString = connectionString
};
string? endpoint = builder["AccountEndpoint"]?.ToString();

This is how the .NET SDK itself parses connection strings. (source)

I know I can get the .Endpoint once I get the CosmosClient back

 let endpointUri : Uri = Microsoft.Azure.Cosmos.CosmosClient(connStr).Endpoint

But that's way too heavy for my taste :(

Related