0

I need to connect to blob storage container and retrieve the data inside the container. I do not have connection string I need to connect via access token. I have the code communicating with blob using connection string. Could anyone modify the code based on communicating with access key and retrieve those data from the container.

string storageConnectionString = "";
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString);
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("ContainerName");
CloudBlockBlob blob = container.GetBlockBlobReference("FileName");
string xmlFile = blob.DownloadTextAsync().Result;
Console.WriteLine(xmlFile);

Kishore
  • 15
  • 1
  • 4
  • What kind of token are specifically talking about? Azure AD token? If so there is [setup you need to do](https://learn.microsoft.com/en-us/azure/storage/common/storage-auth-aad-app?tabs=dotnet) if not done already. – Crowcoder Nov 24 '21 at 13:44

1 Answers1

2

Here is the code that worked for me:

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

namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            string storageAccountName = "<YOUR STORAGE ACCOUNT>";
            string containerName = "<YOUR CONTAINER NAME>";
            string sasToken = "<YOUR SAS TOKEN>";
            StorageCredentials creds;
            CloudBlobContainer cloudBlobContainer;
            creds = new StorageCredentials(sasToken);

            cloudBlobContainer = new CloudBlobContainer(new Uri("https://" + storageAccountName + ".blob.core.windows.net/" + containerName), creds);
            BlobContinuationToken blobContinuationToken = null;
            var blobs = cloudBlobContainer.ListBlobsSegmentedAsync("", blobContinuationToken);
            var blob = blobs.Result;
            foreach (var i_blob in blob.Results)
            {
                Console.WriteLine(i_blob.Uri);
            }

            Console.ReadKey();
        }
    }
}

Result:

enter image description here

References:

Access blob by sas token

halfer
  • 19,824
  • 17
  • 99
  • 186
SwethaKandikonda
  • 7,513
  • 2
  • 4
  • 18
  • I am getting error in this line "var blob = blobs.Result;" -> public access not permitted on this account – Kishore Nov 25 '21 at 05:26
  • I hope you are installing Microsoft.WindowsAzure.Storage.Auth and Microsoft.WindowsAzure.Storage.Blob nuget packages. if that still doesn't work , Can you please try foreach (var i_blob in blobs.Results) and remove the line that you are receiving the error. – SwethaKandikonda Nov 25 '21 at 08:22
  • Is your issue resolved? – SwethaKandikonda Nov 29 '21 at 07:14