Manage storage account resources with .NET

This article shows you how to manage storage account resources by using the Azure Storage management library for .NET. You can create and update storage accounts, list storage accounts in a subscription or resource group, manage storage account keys, and delete storage accounts. You can also configure client options to use a custom retry policy or set other options.

Prerequisites

Set up your environment

If you don't have an existing project, this section walks you through preparing a project to work with the Azure Storage management library for .NET. To learn more about project setup, see Get started with Azure Storage management library for .NET.

Install packages

From your project directory, install packages for the Azure Storage Resource Manager and Azure Identity client libraries using the dotnet add package command. The Azure.Identity package is needed for passwordless connections to Azure services.

dotnet add package Azure.Identity
dotnet add package Azure.ResourceManager.Storage

Add using directives

Add these using directives to the top of your code file:

using Azure.Identity;
using Azure.ResourceManager;

Create an ArmClient object

To connect an application and manage storage account resources, create an ArmClient object. This client object is the entry point for all ARM clients. Since all management APIs go through the same endpoint, you only need to create one top-level ArmClient to interact with resources.

The following example creates an ArmClient object authorized using DefaultAzureCredential, then gets the subscription resource for the specified subscription ID:

ArmClient armClient = new ArmClient(new DefaultAzureCredential(), new ArmClientOptions { Environment = ArmEnvironment.AzureChina });

// Create a resource identifier, then get the subscription resource
ResourceIdentifier resourceIdentifier = new($"/subscriptions/{subscriptionId}");
SubscriptionResource subscription = armClient.GetSubscriptionResource(resourceIdentifier);

To learn about creating client object for a resource group or storage account resource, see Create a client for managing storage account resources.

Authorization

Azure provides built-in roles that grant permissions to call management operations. Azure Storage also provides built-in roles specifically for use with the Azure Storage resource provider. To learn more, see Built-in roles for management operations.

Create a storage account

You can asynchronously create a storage account with specified parameters. If a storage account already exists and a subsequent create request is issued with the same parameters, the request succeeds. If the parameters are different, the storage account properties are updated. For an example of updating an existing storage account, see Update the storage account SKU.

Each storage account name must be unique within Azure. To check for the availability of a storage account name, you can use the following method:

The following code example shows how to check the availability of a storage account name:

// Check if the account name is available
bool? nameAvailable = subscription
    .CheckStorageAccountNameAvailability(new StorageAccountNameAvailabilityContent(storageAccountName)).Value.IsNameAvailable;

You can create a storage account using the following method from the StorageAccountCollection class:

When creating a storage account resource, you can set the properties for the storage account by including a StorageAccountCreateOrUpdateContent instance in the content parameter.

The following code example creates a storage account and configures properties for SKU, kind, location, access tier, and shared key access:

public static async Task<StorageAccountResource> CreateStorageAccount(
    ResourceGroupResource resourceGroup,
    string storageAccountName)
{
    // Define the settings for the storage account
    AzureLocation location = AzureLocation.ChinaEast2;
    StorageSku sku = new(StorageSkuName.StandardLrs);
    StorageKind kind = StorageKind.StorageV2;

    // Set other properties as needed
    StorageAccountCreateOrUpdateContent parameters = new(sku, kind, location)
    {
        AccessTier = StorageAccountAccessTier.Cool,
        AllowSharedKeyAccess = false,
    };

    // Create a storage account with defined account name and settings
    StorageAccountCollection accountCollection = resourceGroup.GetStorageAccounts();
    ArmOperation<StorageAccountResource> accountCreateOperation = 
        await accountCollection.CreateOrUpdateAsync(WaitUntil.Completed, storageAccountName, parameters);
    StorageAccountResource storageAccount = accountCreateOperation.Value;

    return storageAccount;
}

List storage accounts

You can list storage accounts in a subscription or a resource group. The following code example takes a SubscriptionResource instance and lists storage accounts in the subscription:

public static async Task ListStorageAccountsForSubscription(SubscriptionResource subscription)
{
    await foreach (StorageAccountResource storageAccount in subscription.GetStorageAccountsAsync())
    {
        Console.WriteLine($"\t{storageAccount.Id.Name}");
    }
}

The following code example takes a ResourceGroupResource instance and lists storage accounts in the resource group:

public static async Task ListStorageAccountsInResourceGroup(ResourceGroupResource resourceGroup)
{
    await foreach (StorageAccountResource storageAccount in resourceGroup.GetStorageAccounts())
    {
        Console.WriteLine($"\t{storageAccount.Id.Name}");
    }
}

Manage storage account keys

You can get storage account access keys using the following method:

This method returns an iterable collection of StorageAccountKey instances.

The following code example gets the keys for a storage account and writes the names and values to the console for example purposes:

public static async Task GetStorageAccountKeysAsync(StorageAccountResource storageAccount)
   {
    AsyncPageable<StorageAccountKey> acctKeys = storageAccount.GetKeysAsync();
    await foreach (StorageAccountKey key in acctKeys)
    {
        Console.WriteLine($"\tKey name: {key.KeyName}");
        Console.WriteLine($"\tKey value: {key.Value}");
    }
}

You can regenerate a storage account access key using the following method:

This method regenerates a storage account key and returns the new key value as part of an iterable collection of StorageAccountKey instances.

The following code example regenerates a storage account key:

public static async Task RegenerateStorageAccountKey(StorageAccountResource storageAccount)
{
    StorageAccountRegenerateKeyContent regenKeyContent = new("key1");
    AsyncPageable<StorageAccountKey> regenAcctKeys = storageAccount.RegenerateKeyAsync(regenKeyContent);
    await foreach (StorageAccountKey key in regenAcctKeys)
    {
        Console.WriteLine($"\tKey name: {key.KeyName}");
        Console.WriteLine($"\tKey value: {key.Value}");
    }
}

Update the storage account SKU

You can update existing storage account settings by passing updated parameters to one of the following methods:

The following code example updates the storage account SKU from Standard_LRS to Standard_GRS:

public static async Task UpdateStorageAccountSkuAsync(
    StorageAccountResource storageAccount,
    StorageAccountCollection accountCollection)
{
    // Update storage account SKU
    var currentSku = storageAccount.Data.Sku.Name;  // capture the current SKU value before updating
    var kind = storageAccount.Data.Kind ?? StorageKind.StorageV2;
    var location = storageAccount.Data.Location;
    StorageSku updatedSku = new(StorageSkuName.StandardGrs);
    StorageAccountCreateOrUpdateContent updatedParams = new(updatedSku, kind, location);
    await accountCollection.CreateOrUpdateAsync(WaitUntil.Completed, storageAccount.Data.Name, updatedParams);
    Console.WriteLine($"SKU on storage account updated from {currentSku} to {storageAccount.Get().Value.Data.Sku.Name}");
}

Delete a storage account

You can delete a storage account using the following method:

The following code example shows how to delete a storage account:

public static async Task DeleteStorageAccountAsync(StorageAccountResource storageAccount)
{
    await storageAccount.DeleteAsync(WaitUntil.Completed);
}

Configure ArmClient options

You can pass an ArmClientOptions instance when creating an ArmClient object. This class allows you to configure values for diagnostics, environment, transport, and retry options for a client object.

Example: Configure retry options

The following code example shows how to configure the ArmClient object to use a custom retry policy:

// Provide configuration options for the ArmClient
ArmClientOptions armClientOptions = new()
{
    Retry = {
        Delay = TimeSpan.FromSeconds(2),
        MaxRetries = 5,
        Mode = RetryMode.Exponential,
        MaxDelay = TimeSpan.FromSeconds(10),
        NetworkTimeout = TimeSpan.FromSeconds(100)
    },
    Environment = ArmEnvironment.AzureChina
};

// Authenticate to Azure and create the top-level ArmClient
ArmClient armClient = new(new DefaultAzureCredential(), subscriptionId, armClientOptions);

If you don't specify a custom retry policy, the default retry values are used. The following table lists the properties of the RetryOptions class, along with the type, a brief description, and the default value:

Property Type Description Default value
Delay TimeSpan The delay between retry attempts for a fixed approach or the delay on which to base calculations for a backoff-based approach. If the service provides a Retry-After response header, the next retry is delayed by the duration specified by the header value. 0.8 second
MaxDelay TimeSpan The maximum permissible delay between retry attempts when the service doesn't provide a Retry-After response header. If the service provides a Retry-After response header, the next retry is delayed by the duration specified by the header value. 1 minute
MaxRetries int The maximum number of retry attempts before giving up. 3
Mode RetryMode The approach to use for calculating retry delays. Exponential
NetworkTimeout TimeSpan The timeout applied to an individual network operation. 100 seconds

As you configure retry options for an ArmClient object, it's important to note that the scale targets are different between the Storage resource provider (management plane) and the data plane. Be sure to configure retry options with these limits in mind.

If you exceed the rate limit for Azure Storage management plane APIs, you receive an HTTP status code 429 Too Many Requests, which indicates that the request is being throttled. The response includes a Retry-After value, which specifies the number of seconds your application should wait (or sleep) before sending the next request. If you send a request before the retry value elapses, your request isn't processed and a new Retry-After value is returned.

Resources

To learn more about resource management using the Azure management library for .NET, see the following resources.

Code samples

REST API operations

The Azure SDK for .NET contains libraries that build on top of the Storage resource provider REST API, allowing you to interact with REST API operations through familiar .NET paradigms. The management library methods for managing storage account resources use REST API operations described in the following article: