Getting a reference to a blob using its URI

2019-09-21 14:29发布

问题:

How do we get a blob reference via URI?

I'm getting a reference to a blob like so:

        var blob = new CloudBlockBlob(new Uri("https://xxxx.blob.core.windows.net/input/DisabledFlights[1].cache"));

The way I got this URL, is through the portal:

When attempting to download it:

            await blob.DownloadToStreamAsync(stream);

I'm getting the following exception:

[7/17/2019 4:25:27 PM] Executed 'sFtpSender' (Failed, Id=4943c931-5850-4dc8-abe4-c111ed6bbfa9)
[7/17/2019 4:25:27 PM] System.Private.CoreLib: Exception while executing function: sFtpSender. Microsoft.WindowsAzure.Storage: The specified resource does not exist.

What am I doing wrong? How do I get a reference to a blob?

回答1:

As per the error message, I think the blob is in private container.

There're 2 methods for get a blob reference using its uri.

Method 1: Change the container Access Level to Blob level or Container level, then you can directly use the code below:

var blob = new CloudBlockBlob(new Uri("https://xxxx.blob.core.windows.net/input/DisabledFlights[1].cache"));

await blob.DownloadToStreamAsync(stream);

Method 2:If you want to keep the container as private, when initiate a CloudBlockBlob(), you should specify StorageCredentials within it, like below:

//besides using sas token, you can also use other way to construct StorageCredentials, like using account_name / account_key.
var blob = new CloudBlockBlob(new Uri("https://xxxx.blob.core.windows.net/input/DisabledFlights[1].cache"), ,new StorageCredentials("sasToken"));

await blob.DownloadToStreamAsync(stream);


回答2:

Try this:

var blobName = new CloudBlockBlob(new Uri("https://xxxx.blob.core.windows.net/input/DisabledFlights[1].cache")).Name;

CloudBlockBlob blockBlob = _container.GetBlockBlobReference(blobName);

where _container is CloudBlobContainer then

await blockBlob.DownloadToStreamAsync(stream);