Intro

In previous post I have described how to work with Azure Blob Service containers. In this post I am going to show how to work with Azure Blob Service blobs from code.

Prerequisites

Refer to previous posts to get started with Azure Blob Service.

Code

Azure Storage supports three types of blobs:

  • Block blobs are optimized for uploading and downloading large amounts of data efficiently. For most scenarios requiring a blob, a block blob is what you will want to use.
  • Page blobs are a collection of 512-byte pages optimized for random read and write operations.
  • An append blob is comprised of blocks and is optimized for append operations.

All types of blobs support a set of common operations.

The following code will output urls of all blobs in the container:

foreach (var listBlobItem in container.ListBlobs())
{
    Console.WriteLine(listBlobItem.Uri);
}

You can filter the list of blobs by specifying a part of the blob name:

container.ListBlobs("part-of-the-name");

There are couple more parameters that are used by ListBlobs method, I will describe them in future posts.

Lets assume we have a blob blob.dat of unknown type. We can work with this blob somehow, but some specific operations are not available. Fortunately we can get blob type using following code:

var blob = container.GetBlobReferenceFromServer("blob.dat");
Console.WriteLine(blob.BlobType);

Make sure you use GetBlobReferenceFromServer because GetBlobReference won't fetch BlobType from server by default, you will have to do it explicitly:

var blob = container.GetBlobReference("blob.dat");
blob.FetchAttributes();
Console.WriteLine(blob.BlobType);

It is impossible to write data to a blob of base type, you will have to cast it to CloudBlockBlob, CloudPageBlob or CloudAppendBlob to get access to all set of methods available for this type of blob. It can be done like this:

var blob = container.GetBlobReferenceFromServer("blob.dat");
var blockBlob = blob as CloudBlockBlob;
Console.WriteLine(blockBlob);

You can read get contents of blob from server regardles its type using one of following methods:

  • DownloadRangeToByteArray
  • DownloadRangeToStream
  • DownloadToByteArray
  • DownloadToFile
  • DownloadToStream

These methods have self-explanatory names. Another option is to read blob as a stream:

var blob = container.GetBlobReference("blob.dat");
using (var stream = blob.OpenRead())
{
    // your code here
}

Summary

In this post I briefly described different types of blobs. You can find more information at Understanding Block Blobs, Append Blobs, and Page Blobs. In the next post I am going to focus on blobs leasing.


;