Creating Azure BlobClient from Uri and BlobServiceClient

In Azure Storage v12 SDK, how can I create a blob client with Blob URI and BlobServiceClient?

In v11, we could do this by:

var cloudBlockBlob = new CloudBlockBlob(<Blob URI>, <Cloud Blob Client>);

I have managed to do this in the following hacky way where I had to get the container and the client name by creating a blobClient object initially. I could not access the blob using the initial client as I was getting AuthenticationFailed error.

var sasUri = _blobServiceClient.GenerateAccountSasUri(
    AccountSasPermissions.Read, DateTimeOffset.UtcNow.AddDays(10),
        AccountSasResourceTypes.Object);
var sasCredential = new AzureSasCredential(sasUri.ToString());

// this is not valid as I get an Authentication Exception if I try to access from here
var blobClient = new BlobClient(blobUri, sasCredential); 

BlobContainerClient blobContainerClient = 
    _blobServiceClient.GetBlobContainerClient(blobClient.BlobContainerName);
blobClient = blobContainerClient.GetBlobClient(blobClient.Name);
BlobDownloadInfo blobDownloadInfo = await blobClient.DownloadAsync(cancellationToken);

I am pretty sure I am doing something wrong here and there is a better way of doing this. How can I achieve this in v12 properly?

Answer

Ivan’s answer is correct. Essentially the problem is that AzureSasCredential expects a SAS token and not a URL.

An alternate way of getting the token from SAS URL is:

var sasCredential = new AzureSasCredential(sasUri.Query);

Leave a Reply

Your email address will not be published. Required fields are marked *