Download Azure Blob using SAS key in .net

Viewed 1613

I am trying to access Azure Blob with SAS token to download the data from the blob, this is what I have tried.

I am very new to this so have no idea how it should work

this is what I have tried so far.

            const string sasToken = "SAS TOKEN";
  
            var blobUri = new System.Uri("URI");

            var blobUriBuilder = new System.UriBuilder(blobUri)
            {
                Query = sasToken
            };

            var authorizedBlobUri = blobUriBuilder.Uri;
            var blobClient = new BlobClient(authorizedBlobUri);

            Console.WriteLine("blob read successfully: {0} ", blobClient.BlobContainerName);

            // Create a local file in the ./data/ directory for uploading and downloading
            string localPath = "./data/";
            string fileName = "quickstart" + Guid.NewGuid().ToString() + ".txt";
            string localFilePath = Path.Combine(localPath, fileName);

            string downloadFilePath = localFilePath.Replace(".txt", "DOWNLOADED.txt");
           
            var response = await blobClient.DownloadToAsync(downloadFilePath);
            Console.WriteLine("blob read successfully: {0} {1}", response.Content, response.Status);

Error is enter image description here

could you suggest if this is the right way to get data from the Blob and how to resolve this error I am getting please

1 Answers

Would suggest you to please use this below code share in GITHUB from one of their community members.

using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;

namespace AzureBlobStorage
{
    internal static class Program
    {
        private static void Main()
        {
            const string accountName = "account-name";
            const string blobContainerName = "blob-container-name";
            const string downloadLocation = @"C:\data";
            const string sasToken =
                @"<SAS token (just the token, not the URI)>";
            
            // Create a credential object from the SAS token then use this and the account name to create a cloud storage connection
            var accountSAS = new StorageCredentials(sasToken);
            var storageAccount = new CloudStorageAccount(accountSAS, accountName, null, true);

            // Get the Blob storage container
            var blobClient = storageAccount.CreateCloudBlobClient();
            var container = blobClient.GetContainerReference(blobContainerName);

            // Fail if the container does not exist
            if (!container.Exists())
            {
                Console.Error.WriteLine($"Can't find container '{blobContainerName}'");
                return;
            }

            // Get the list of blobs in the container, just for demo purposes this is ordered by blob name and taking only
            // the first 10 items
            var blobs = container
                .ListBlobs(blobListingDetails: BlobListingDetails.Metadata)
                .OfType<CloudBlob>()
                .OrderBy(blobItem => blobItem.Name)
                .Take(10)
                .ToList();

            // Set the request options to ensure we're performing MD5 validation
            var downloadOptions = new BlobRequestOptions
            {
                DisableContentMD5Validation = false,
                UseTransactionalMD5 = true
            };

            // Download the files
            // The parameters are named for reference only and can safely be removed
            Task.WaitAll(
                blobs.Select(
                    blobItem => blobItem.DownloadToFileAsync(
                        path: Path.Combine(downloadLocation, blobItem.Name),
                        mode: FileMode.Create, 
                        accessCondition: null, 
                        options: downloadOptions, 
                        operationContext: null)).ToArray());
        }
    }
}

Reference: https://gist.github.com/dazfuller/9b5ea145525879fb5114bd78b53e9ee5#file-azureblobdownload-cs

Related