William Edmondson
William Edmondson

Reputation: 3635

Create BlobContainerClient from Azure SAS URI

In the Microsoft.Azure.Storage.Blob library you could create a blob upload client using a SAS URI.

var cloudBlockBlob = new CloudBlockBlob(blobSasUri);

However, this library has been deprecated in favor of Azure.Storage.Blobs. I am unsure how to create an instance of BlobContainerClient using a SAS URI since none of the class's constructors allow for a URI parameter. Is this even possible? Or do I need to just use an HttpClient to call the Blob service?

Upvotes: 3

Views: 10715

Answers (2)

Ivan Glasenberg
Ivan Glasenberg

Reputation: 30035

In the library Azure.Storage.Blobs, you can create the BlobContainerClient instance by using this constructor:

public BlobContainerClient(Uri blobContainerUri, BlobClientOptions options = null);

For example, you have a container sas uri like below:

"https://xxx.blob.core.windows.net/mycontainer111?sv=2019-12-12&ss=bfqt&srt=sco&sp=rwdlacupx&se=2020-10-27T08:45:57Z&st=2020-10-27T00:45:57Z&spr=https&sig=xxxxxx";

Then you can use the code below to create BlobContainerClient instance:

        string sasuri = "https://xxx.blob.core.windows.net/mycontainer111?sv=2019-12-12&ss=bfqt&srt=sco&sp=rwdlacupx&se=2020-10-27T08:45:57Z&st=2020-10-27T00:45:57Z&spr=https&sig=xxxxxx";
        Uri container_uri = new Uri(sasuri);
        var container_client = new BlobContainerClient(container_uri);

        //other code

Upvotes: 8

user3026017
user3026017

Reputation: 939

Indeed, it seems that it has been deprecated in favor of Azure.Storage.Blobs.

You need to create get a reference to the CloudBlobContainer from the container where you want to upload to:

var connectionString = String.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}",
    storageAccountName, // your storage account name
    accessKey); // your storage account access key

var storageAccount = CloudStorageAccount.Parse(connectionString);
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("my-container");

Specify and retrieve the sas URI

SharedAccessBlobPolicy sasConstraints = new SharedAccessBlobPolicy();
sasConstraints.SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(30);
sasConstraints.Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Create;

var sasUri = blob.GetSharedAccessSignature(sasConstraints);

Upload files:

var cloudBlockBlob = new CloudBlockBlob(new Uri(sasUri));
await cloudBlockBlob.UploadFromFileAsync(@"c:\myfile.txt");

More details at this link

Upvotes: -1

Related Questions