Monday, October 11, 2010

Testing Existence of a Windows Azure Blob


A question came up today on Stack Overflow of how to test for the existence of a blob. From the REST API, the best method seems to be Get Blob Properties, which does a HEAD request against the blob. That will return a404 if the blob doesn’t exist, and if the blob does exist, it only returns the headers that would typically come with the blob contents. This makes it an efficient way to test for the existence of a blob.
From the .NET StorageClient library, the method which maps to Get Blob Properties isCloudBlob.FetchAttributes(). The following extension method implements an Exists() method onCloudBlob:
public static class BlobExtensions
{
    public static bool Exists(this CloudBlob blob)
    {
        try
        {
            blob.FetchAttributes();
            return true;
        }
        catch (StorageClientException e)
        {
            if (e.ErrorCode == StorageErrorCode.ResourceNotFound)
            {
                return false;
            }
            else
            {
                throw;
            }
        }
    }
}
Using this extension method, we can test for the existence of a particular blob in a natural way. Here’s a little program that tells you whether a particular blob exists:
static void Main(string[] args)
{
    var blob = CloudStorageAccount.DevelopmentStorageAccount
        .CreateCloudBlobClient().GetBlobReference(args[0]);
    // or CloudStorageAccount.Parse("<your connection string>")

    if (blob.Exists())
    {
        Console.WriteLine("The blob exists!");
    }
    else
    {
        Console.WriteLine("The blob doesn't exist.");
    }
}
Note that the above extension method has a side-effect, in that it fills in the CloudBlob.Attributesproperty. This is probably fine (and an optimization if you’re later going to read those attributes), but I thought I’d point it out.
[UPDATE 4/19/2010] This same technique works great with containers also. Here’s a similar extension method on CloudBlobContainer:
public static class ContainerExtensions
{
    public static bool Exists(this CloudBlobContainer container)
    {
        try
        {
            container.FetchAttributes();
            return true;
        }
        catch (StorageClientException e)
        {
            if (e.ErrorCode == StorageErrorCode.ResourceNotFound)
            {
                return false;
            }
            else
            {
                throw;
            }
        }
    }
}

No comments:

Post a Comment