Azure BLOB Storage Services

This post is a quick guide to start dealing with Azure BLOB Storage Services. I will create a simple .Net Console Application to upload and download a simple file within BLOB Storage Services. Before going ahead, I highly recommend take a look to How to create an Azure Storage Account. It is not complex but mandatory before interacting with BLOB Storage Services.

Background

Here is the access keys screen you can access from azure portal:

I will use the Storage account st001jamuroblogengine to create a simple .Net Console Project to upload a "HelloWorld.txt" file to a container in Azure BLOB Storage Services, download it by using the same .Net client and besides, provide a public URL to download the file from any browser. I take for granted you already know how to create a .Net Console project. So, getting straight to the point, here is the sample code from the entry point class in the console application:

Note: Use the Nuget Package Manager to include the WindowsAzure.Storage package to the project before adding the code.

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

namespace Jamuro.AzureLearning.BasicsToConnectAzureStorageBlobs
{
    static class Program
    {
        static void Main(string[] args)
        {

            string m_sampleFileDirectory = ConfigurationManager.AppSettings.Get("SampleFilesDirectory");
            string m_storageConnectionString = ConfigurationManager.AppSettings.Get("StorageConnectionString");
            string m_containerName = ConfigurationManager.AppSettings.Get("ContainerName");
            string m_blobName = "HelloWorld";

            // Retrieve storage account from connection string.
            CloudStorageAccount stAccount = CloudStorageAccount.Parse(m_storageConnectionString);

            // Create the blob client.
            CloudBlobClient blobClient = stAccount.CreateCloudBlobClient();

            // Retrieve a reference to a specific container.
            CloudBlobContainer blobContainer = blobClient.GetContainerReference(m_containerName);

            // Create the container if it doesn't already exist.
            blobContainer.CreateIfNotExists();

            // Set permissions to give public access to the blob
            blobContainer.SetPermissions(new BlobContainerPermissions{ PublicAccess = BlobContainerPublicAccessType.Container });

            // Retrieve reference to a blob named "HelloWorld".
            CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference(m_blobName);

            // Create or overwrite the blob with contents from a local file.
            using (var fileStream = System.IO.File.OpenRead($@"{m_sampleFileDirectory}\{m_blobName}.txt"))
            {
                Console.WriteLine($"Uploading {m_blobName} Blob...");
                blockBlob.UploadFromStream(fileStream);
                Console.WriteLine($"Successfully Uploaded {m_blobName} Blob!");
                Console.WriteLine($"{Environment.NewLine}Please, press ENTER to continue...");         
                Console.ReadLine();
            }

            // Save blob contents to a file.
            string downloadedFilePath = $@"{m_sampleFileDirectory}\{m_blobName}.Downloaded.txt";
            using (var fileStream = System.IO.File.OpenWrite(downloadedFilePath))
            {
                Console.WriteLine($"Downloading {m_blobName} Blob...");          
                blockBlob.DownloadToStream(fileStream);
                Console.WriteLine($"Successfully Downloaded {m_blobName} Blob to {downloadedFilePath}");
                Console.WriteLine($"{Environment.NewLine}Please, press ENTER to continue...");
                Console.ReadLine();
            }

            // List blobs stored the container
            foreach (IListBlobItem blob in blobContainer.ListBlobs())
            {
                if (blob.GetType() == typeof(CloudBlockBlob))
                {
                    Console.WriteLine($"You also can download the {m_blobName} blob from: {Environment.NewLine}{blob.Uri}");
                }
                Console.ReadLine();
            }

        }
    }
}

Here is the app.config file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>
  <appSettings>
    <add key="StorageConnectionString" value="DefaultEndpointsProtocol=https;AccountName=st001jamuroblogengine;AccountKey={Paste your account key from keys section in your Azure account};EndpointSuffix=core.windows.net" />
    <add key="ContainerName" value="container001"></add>
    <add key="SampleFilesDirectory" value="C:\Users\jmuro\Documents\"/>
  </appSettings>
</configuration>

Here are the results from the console:

Try to download the BLOB from: https://st001jamuroblogengine.blob.core.windows.net/container001/HelloWorld 

You should be able to download it as the .Net Console project is assigning Public read access for the container and its blobs. It means any anonymous user can not only read all the BLOBs within the container but iterate or enumerate BLOBs as well. Containers for BLOBs can also be configured with No public read access (only accessible by the storage account owner) and Public read access for blobs only (only BLOBs are accessible, not allowed to iterate or enumerate over containers)

References

How to create an Azure Storage Account | Azure Storage REST API Reference |  Blob service REST API | Microsoft Azure Storage SDK for .NET 

Add comment