Search code examples
c#azureblobazure-blob-storage

How to connect to blob storage container using c#


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);


Solution

  • 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