kumar
kumar

Reputation: 9387

C# Get list of containers in a Cosmos Database

How do I get list of container for a Cosmos Database using C#

var client2 = new CosmosClient("https://MYCOSMOS.documents.azure.com:443/", "kpWBLj8jfN0qDPsdfsg1Amng==");
client2.GetDatabase("").GetContainer("");

There is no option for GetContainers()

Upvotes: 3

Views: 5160

Answers (1)

Kiril1512
Kiril1512

Reputation: 3611

You can archive this by this way:

private readonly CosmosClient databaseClient;

public CosmosDbManager(CosmosClient dataBaseClient)
{
    this.databaseClient = dataBaseClient;
}

public async Task GetContainer(CosmosDbConfiguration configuration)
{
    Database database = this.databaseClient.GetDatabase(configuration.Database);
    FeedIterator<ContainerProperties> iterator = database.GetContainerQueryIterator<ContainerProperties>();
    FeedResponse<ContainerProperties> containers = await iterator.ReadNextAsync().ConfigureAwait(false);

    foreach (var container in containers)
    {
        // do what you want with the container
    }
}

In your case:

CosmosClient client2 = new CosmosClient("https://MYCOSMOS.documents.azure.com:443/", "kpWBLj8jfN0qDPsdfsg1Amng==");

Database database = this.client2.GetDatabase(configuration.Database);
FeedIterator<ContainerProperties> iterator = database.GetContainerQueryIterator<ContainerProperties>();
FeedResponse<ContainerProperties> containers = await iterator.ReadNextAsync().ConfigureAwait(false);

foreach (var container in containers)
{
    // for examploe container.id will return the name of your container
}

Upvotes: 8

Related Questions