download from blob when given its uri fails in c#

2019-08-28 20:24发布

问题:

I'm trying to download a file from Azure blob and save it locally, but it seems to fail. Here's the relevant code:

    var blobClientCode = client.CreateCloudBlobClient();
    string codeUri = "https://???.blob.core.windows.net/...../mycode.exe";
    using (var codeContent = File.OpenWrite("C:\\code.exe")) {
        blobClientCode.GetBlockBlobReference(codeUri).DownloadToStream(codeContent);
    }

I get an error in which the container doens't exist. What am I doing wrong?

回答1:

Try getting a reference to the container first then defining the CloudBlockBlob from this using just the relative path.

This is the code that works for me:

CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("myContainerName");

CloudBlockBlob blockBlob = container.GetBlockBlobReference("/subfolder/filename.exe");
using (fileStream == System.IO.File.OpenWrite("C:\code.exe")) {
    blockBlob.DownloadToStream(fileStream);
}