Jay
Jay

Reputation: 5084

Building a Connection string for a Azure Storage Account Connection String

I know that you can get the Connection string using this:

 <add key="StorageConnectionString" value="DefaultEndpointsProtocol=https;AccountName=mystorage;AccountKey=MY_ACCOUNT_KEY" />

And then retrieve it using this:

CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));

And I know how to build a connection string using SqlConnectionStringBuilder:

System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();
builder["DefaultEndpointsProtocol"] = "https";
builder["AccountName"] = "mystorage";
builder["AccountKey"] = "MY_ACCOUNT_KEY";
string conString = builder.ConnectionString;

However apparently this doesn't work for Storage Connection Strings. It says SqlConnectionStringBuilder doesn't support DefaultEndpointsProtocol or any of the 3 keys I have specified. How can I make a string out of these keys?

Upvotes: 3

Views: 7527

Answers (2)

Shaun Luttin
Shaun Luttin

Reputation: 141512

Answer

Use the CloudStorageAccount constructor that takes a StorageCredentials object. Then use the ToString(boolean) overload to get the connection string.

Demo with Fiddle https://dotnetfiddle.net/ReWDqL

var accountName = "myAccount";
var keyValue = "c3RyaW5nIGxlbmd0aCB2YWxpZA==";
var useHttps = true;
var exportSecrets = true;

var storageCredentials = new StorageCredentials(accountName, keyValue);
var storageAccount = new CloudStorageAccount(storageCredentials, useHttps);
var connString = storageAccount.ToString(exportSecrets);

MSDN Documentation

StorageCredentials Constructor (String, String). Initializes a new instance of the StorageCredentials class with the specified account name and key value.

CloudStorageAccount Constructor (StorageCredentials, Boolean). Initializes a new instance of the CloudStorageAccount class using the specified credentials, and specifies whether to use HTTP or HTTPS to connect to the storage services.

CloudStorageAccount.ToString Method (Boolean). Returns a connection string for the storage account, optionally with sensitive data.

Upvotes: 9

Aram
Aram

Reputation: 5705

Not sure why don't you use the first option that you have working(Maybe you want to keep them separate in your config file), but in any case you can just concat them together to build the string:

var storageConnectionString = String.format("DefaultEndpointsProtocol={0};AccountName={1};AccountKey={2}", "https", "MyAccountName","MyAccountKey");

CloudStorageAccount.Parse(storageConnectionString);

Upvotes: 5

Related Questions