Azure Blob Storage – a simple example

This is for all of you that just want a simple, up to date, example/how-to/tutorial of how to use Azure Blob Storage. You won’t see any screen shots or a lengthy guide on how to get started from scratch. Instead I will just focus on writing some code examples for general stuff that you might like to do. I will keep this simple and avoid getting into more advanced scenarios such as page blobs, VHD and leases. I’ll cover those in posts later on.

All examples below assume that we have already instantiated CloudBlobClient cloudBlobClient. It can be done using the code.

var account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
var cloudBlobClient = account.CreateCloudBlobClient();

Upload a Blob from a string

First example, upload a string as a text file. We, for example, use this to upload crash logs to blob storage and then mail a link to the support team.

public Uri UploadBlob(string path, string fileName, string content)
{
    var cloudBlobContainer = cloudBlobClient.GetContainerReference(path);
    cloudBlobContainer.CreateIfNotExist();

    var blob = cloudBlobContainer.GetBlobReference(fileName);
    blob.UploadText(content);

    return blob.Uri;
}

So if we would call this method using the following parameters.

var uri = UploadBlob("folder", "file.txt", "text in file");

We would get a link pointing at http://yourstorageaccount.blob.core.windows.net/folder/file.txt containing the text – “text in file”. Please note that this call is made synchronously.

Upload a Blob from a stream

You will recognize this from the previous example. The difference is that we are using a stream instead of a string and that the call is made asynchronously.

public void UploadBlob(string path, string fileName, Stream stream)
{
    var cloudBlobContainer = cloudBlobClient.GetContainerReference(path);
    cloudBlobContainer.CreateIfNotExist();

    var blob = cloudBlobContainer.GetBlobReference(fileName);
    blob.BeginUploadFromStream(stream, UploadFinished, blob.Uri);
}

private void UploadFinished(IAsyncResult asyncResult)
{
    // do something
}

List all Blobs in a container

This will give a list of links to all blobs stored in a container.

public IEnumerable<Uri> ListAllBlobs(string folder)
{
    var cloudBlobContainer = cloudBlobClient.GetContainerReference(folder);
    var listBlobItems = cloudBlobContainer.ListBlobs();

    return listBlobItems.Select(b => b.Uri);
}

Simple enough. Once you got the setup right, Azure Blob Storage is actually quite easy to use. If you would like to list blobs in subfolders as well then use the overloaded method for ListBlobs and send in BlobRequestOptions { UseFlatBlobListing = true }.

blob storage

 

Download content from a Blob

Very similar to uploading data, it works the same way with other data types than string.

public string DownloadBlob(string folder, string fileName)
{
    var cloudBlobContainer = cloudBlobClient.GetContainerReference(folder);
    var blob = cloudBlobContainer.GetBlobReference(fileName);

    return blob.DownloadText();
}

But, before downloading a blob, you might want to see if it exists…

See if a Blob exists

The only way that I have found for doing this (and please correct me if I’m wrong here) is to do a little peek and catch the resulting exception.

private bool BlobExists(CloudBlob blob)
{
    try
    {
        blob.FetchAttributes();
        return true;
    }
    catch (StorageClientException e)
    {
        if (e.ErrorCode == StorageErrorCode.ResourceNotFound)
        {
            return false;
        }
        throw;
    }
}

Thanks to Steve Marx for the solution. FetchAttributes() is used simply because it will be a small amount of data transferred or a 404. So even if I call BlobExists() on a 4Mb block blob it won’t be any different from doing the same call on a 2Kb blob.

Some tips and tricks

Well, first of all. Azure Blob storage can be used for much more than just file storage. Scalability is built in so if you, for example, have a static html page, you can easily upload it to Azure blob storage and then link to it. It is a good way to take away load from your WebRole.

All methods that I showed you have a Begin/End method as well. So you should be able to do most of the work asynchronously, as I did when I uploaded a blob from a stream.

If an Azure Queue message risk becoming bigger than 8Kb the recommended solution is to upload the message as a blob and then store the URI as the message on the queue. You won’t get charged for the extra data traffic as long as it’s done within the same data center.

Happy blobbing.

This Post Has 5 Comments

  1. thanks for the samples – is there a way to append to a blob without downloading it

  2. It really is in fact a fantastic as well as useful section of facts. I’m thankful for you to shared this helpful facts around. You should remain united states advised such as this. Thank you giving.

  3. How i can create Subdirectory in Container?

    For Ex:

    Container
    Mydirectory
    MySubdirectory

  4. can’t you See if a Blob exists by blob.exists() ? It will return you true or false.

Leave a Reply

Close Menu